我正在为 Array 编写一个扩展方法,它接受一个函数,然后为 Array 中的每个项目调用它。
它工作正常,除了扩展本身在函数调用后被添加到数组中。所以在警报部分,第三个警报以字符串形式显示我的 foo 函数。
代码如下:
Array.prototype.foo = function (F) {
for (var i in this) {
this[i] = F(this[i]);
}
}
var items = ["a", "b"];
items.foo(function (data) {
return data + 1;
});
for (var i in items) {
alert(items[i]); // expected to see a1 and b1 but also displayed foo as string.
}
最佳答案
那是因为for in
遍历数组的键,而不是元素。你会想要切换你的循环(我相信):
for (var e = 0; e < this.length; e++){
// call against this[e] now
}
例如:
var ary = ['a','b','c']
for (var a = 0; a < ary.length; a++){
console.log(ary[a]); // echos a, b, c
}
var obj = {a:'X',b:'Y',c:'Z'}
for (var a in obj){
console.log(a); // echos a, b, c
console.log(obj[a]) // echos X, Y, Z
}
关于数组上的 JavaScript 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8347723/