数组上的 JavaScript 扩展

标签 javascript

我正在为 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/

相关文章:

javascript - 使用 Bootstrap 工具提示和 jQuery 进行验证?

javascript - HTML 中的绝对路径不起作用

javascript - 我似乎无法使这个 if 语句在 Javascript 中工作 :S

javascript - 从 javascript 书签调用 Devise

javascript - 执行动态加载的 JavaScript

javascript - 动态创建的 Jquery 嵌套元素的 css 样式和 js 事件已损坏

javascript - 将 JSON 查询条件转换为 MongoDB/Mongoose 操作

javascript - 搜索第一个数组中的对象属性值并将其替换为第二个数组中的对象属性值?

javascript - 使用 jQuery.each() 确保输入属于某种类型

javascript - Angular.js Controller 不工作