gpt4 book ai didi

返回多个值的 JavaScript 数组迭代

转载 作者:行者123 更新时间:2023-12-04 00:30:12 24 4
gpt4 key购买 nike

这太简单了,我很困惑。我有以下内容:

var x = 'shrimp';    
var stypes = new Array('shrimp', 'crabs', 'oysters', 'fin_fish', 'crawfish', 'alligator');
for (t in stypes) {
if (stypes[t] != x) {
alert(stypes[t]);
}
}

一旦值被迭代,它开始返回十几个函数,比如

function (iterator, context) {
var index = 0;
iterator = iterator.bind(context);
try {
this._each(function (value) {iterator(value, index++);});
} catch (e) {
if (e != $break) {
throw e;
}
}
return this;
}

这到底是怎么回事?

编辑:在这些脚本中,我使用了 http://script.aculo.us/prototype.jshttp://script.aculo.us/scriptaculous.js我记得现在读过原型(prototype)扩展数组的方式,我敢打赌这是其中的一部分。我该如何处理?

最佳答案

for 枚举将遍历您传递给它的对象的每个 成员。在这种情况下,数组恰好具有作为成员的函数以及传递的元素。

您可以重新编写 for 循环来检查 typeof stypes[t] == "function" 还是 yada yada。但是 IMO 你最好只将循环修改为只有元素..

for(var i = 0, t; t = stypes[i]; ++i){
if (t != x) {
alert(t);
}
}

或者

for(var i = 0; i < stypes.length; ++i){
if (stypes[i] != x) {
alert(stypes[i]);
}
}

我想将我的最后一条评论迁移到答案,以添加第一种循环类型的警告通知。

来自 Simon Willison's "A re-introduction to JavaScript" ..

for (var i = 0, item; item = a[i]; i++) {
// Do something with item
}

Here we are setting up two variables. The assignment in the middle part of the for loop is also tested for truthfulness - if it succeeds, the loop continues. Since i is incremented each time, items from the array will be assigned to item in sequential order. The loop stops when a "falsy" item is found (such as undefined).

Note that this trick should only be used for arrays which you know do not contain "falsy" values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use the i, j idiom instead.

关于返回多个值的 JavaScript 数组迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1495403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com