關於數組遍歷

一般須要進行數組遍歷,會想到使用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

相關文章
相關標籤/搜索