关于数组遍历

一般须要进行数组遍历,会想到使用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新增)。wordpress

[].forEach(function(value, index, array) {
    // ...
});

jQuery中有$.eachthis

$.each([], function(index, value, array) {
    // ...
});

这两个方法适用于如下浏览器版本es5

  • Opera 11+
  • Firefox 3.6+
  • Safari 5+
  • Chrome 8+
  • Internet Explorer 9+

IE6-IE8则能够经过array原型扩展进行实现spa

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方法详细说明prototype

附上网址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/code

相关文章
相关标签/搜索