关于数组遍历
通常需要进行数组遍历,会想到使用for循环语句:
for (var i=0; i<5; i++){
x=x + "The number is " + i + "<br>";
}
因为Vue 的使用,for in语句也比较熟悉
var person={fname:"John",lname:"Doe",age:25}; for (x in person){ txt=txt + person[x]; }
除此之外, js的数组方法就有遍历,forEach(ES5新增)。
[].forEach(function(value, index, array) { // ... });
jQuery中有$.each
$.each([], function(index, value, array) { // ... });
这两个方法适用于以下浏览器版本
- Opera 11+
- Firefox 3.6+
- Safari 5+
- Chrome 8+
- Internet Explorer 9+
IE6-IE8则可以通过array原型扩展进行实现
if (typeof Array.prototype.forEach != "function") { Array.prototype.forEach = function (fn, context) { for (var k = 0, length = this.length; k < length; k++) { if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) { fn.call(context, this[k], k, this); } } }; }
参考 张鑫旭大神的ES5中新增的Array方法详细说明
附上网址http://www.zhangxinxu.com/wordpress/2013/04/es5%E6%96%B0%E5%A2%9E%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95/