Array上的JavaScript扩展(JavaScript extension on 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. }I'm writing an extension method for Array which accepts a function and then call it for each items in the Array.
It works fine except the extension itself is added into the Array after the function call. So at the alert part, the third alert shows my foo function in string.
Here's the code:
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 }That's because for in is going through the keys of the array, not the elements. You'll want to switch your loop (I believe):
for (var e = 0; e < this.length; e++){ // call against this[e] now }For example:
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 }更多推荐
发布评论