JavaScript forEach implementation
JavaScript forEach implementation
我在教程网站上找到了一个forEach
函数的代码片段,除了检查i
是否在数组中的行之外,一切都对我来说很有意义:
if (i in this) {
如果我们已经有一个具有停止条件的 for 循环,为什么要打扰呢?
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function") {
throw new TypeError();
}
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
fun.call(thisp, this[i], i, this);
}
}
};
}
两个原因:
1. 回调突变
调用fun
可能会更改数组,因为fun
完全是用户定义的。所以你需要再次检查。
例:
array.forEach(function (el, i) { delete array[i + 1]; });
2. 稀疏数组
另一个问题是可能存在稀疏数组:例如
3 in ["a", "b", "c", , "e", "f"] === false
// even though
3 in ["a", "b", "c", undefined, "e", "f"] === true
在这些情况下,您不想为该索引/元素调用fun
,因为该索引中没有任何内容。
["a", "b", "c", , "e", "f"].forEach(function (el, i) {
console.log(el + " at " + i);
});
// => "a at 0" "b at 1" "c at 2" "e at 4" "f at 5"
因为数组可以有孔,因此您可以迭代长度,并且并非所有值都存在。
x = new Array()
[]
x[0] = "zero"
"zero"
x[5] = "five"
"five"
x
["zero", undefined × 4, "five"]
3 in x
false
x.length
6
for (var i = 0; i < x.length; i++) { console.log(i, i in x, x[i])}
0 true "zero"
1 false undefined
2 false undefined
3 false undefined
4 false undefined
5 true "five"
相关文章:
- JavaScript jvm implementation
- Implementation of jQuery 'animate' with Meteor
- Lightbox 2 Implementation
- Facebook Accountkit JAVASCRIPT Implementation
- duktape modSearch. Native implementation in C
- JavaScript Implementation of VIM
- Kiosk Web App jQuery Implementation
- JS canvas implementation of Julia set
- CSURF Angular Implementation
- Javascript Draw2d - CanvasRenderingContext2D.implementation不
- JavaScript forEach implementation
- jquery camelcase implementation
- js - kcfinder tinymce implementation
- Dual jsTree Implementation
- Cakephp and Fancybox implementation
- HTML 5 Panotour Pro implementation
- document.implementation.createHTMLDocument浏览器支持
- Hangman implementation
- MD5 javascript implementation
- Django pbkdf2_sha256 JS implementation