Array上的JavaScript扩展(JavaScript extension on Array)

编程入门 行业动态 更新时间:2024-10-28 08:23:47
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 }

更多推荐

本文发布于:2023-07-27 14:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292026.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Array   JavaScript   extension

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!