Array.prototype.each = function(callback){for(var i = 0; i <this.length; i ++)callback(this ); } – 这个可以吗?

我知道这是一个味道的问题,但每次我想迭代数组的时候,我的味道使用for循环是坏的。 所以我想出了这个:

Array.prototype.each = function(callback) { for (var i = 0; i < this.length; i++) callback(this[i]); } 

现在我可以这样做:

 [10, 20, 30].each(function(n) { console.log(n/10) }) 

后来我在互联网上发现了一些提示这种方法的提示,但是我仍然怀疑它是否没有副作用。 这似乎很明显,这是我的担心:)

我没有使用任何类似jQuery或Prototype的库。 我正在为Node.js编码

我build议你使用forEach 。 它是在大多数现代浏览器中实现的,垫片是由MDN提供的。

在node.js上,它实现了(它使用V8,与Chrome相同的引擎),所以你不需要垫片。

它的用法如下:

 arr.forEach( function( el ) { // play with "el" } ) 

另外,我build议你看一下ES5提供的新arrays方法:

  • 地图
  • 过滤
  • 减less
  • 一切
  • 一些

这确实有一个相当大的副作用

如果我们现在运行下面的代码

 a = [10, 20, 30]; for (var i in a) { console.log(i + ": " + a[i]); } 

并检查控制台输出,我们看到这个:

 0: 10 1: 20 2: 30 each: function (callback) { for (var i = 0; i < this.length; i++) callback(this[i]); } 

这限制了你可以在数组上执行循环的types

 a = [10, 20, 30]; for (var i = 0; i < a.length; ++i) { console.log(a[i] + ": " + a[i]); } 

从:

 // Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.io/#x15.4.4.18 if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this === null) { throw new TypeError(' this is null or not defined'); } // 1. Let O be the result of calling toObject() passing the // |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get() internal // method of O with the argument "length". // 3. Let len be toUint32(lenValue). var len = O.length >>> 0; // 4. If isCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let // T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0 k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty // internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Call the Call internal method of callback with T as // the this value and argument list containing kValue, k, and O. callback.call(T, kValue, k, O); } // d. Increase k by 1. k++; } // 8. return undefined }; } 

加上这个使用html元素:

 NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach; 

瞧!