Javascript jQuery.each() 未定义问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3330264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery.each() undefined issue
提问by A-Dubb
I have the following code
我有以下代码
function myFunction(items) {
// this prints out 11
alert(items.length);
$(items).each(function(i, item) {
// item is undefined for some reason
}
}
It I alert the length of items, it has elements in it (11 to be exact). so how could 11 items be present, but jQuery still pass undefined?
我提醒项目的长度,其中包含元素(准确地说是 11 个)。那么怎么可能存在 11 个项目,但 jQuery 仍然通过 undefined?
回答by Matt
The only explanation for this is the that items array contains values which are undefined, i.e :
对此的唯一解释是 items 数组包含未定义的值,即:
items = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];
Both of the other answers are wholly incorrect. The first parameter of eachis the index, not the value, and jQuery.fn.each calls jQuery.each. There is no disambiguation between them.
其他两个答案都是完全错误的。的第一个参数each是索引,不是值,jQuery.fn.each 调用 jQuery.each。它们之间没有歧义。
回答by jAndy
It sounds like you are notpassing a jQuery wrappet setto your function. If you pass
an arrayor an objectyou need to use the jQuery helper function$.each()like
听起来您没有将 a 传递jQuery wrappet set给您的函数。如果您通过 anarray或 anobject您需要使用jQuery helper function$.each() 之类的
$.each(items, function(index, element){
});
As I already mentioned several times in other answers, it is bad practice to loop over an array with .each()or javascripts native for..in.
正如我在其他答案中已经多次提到的那样,使用.each()或 javascripts native遍历数组是不好的做法for..in。
If you are passing arraysuse a standard for loop.
如果您通过,请arrays使用标准for loop.
edit
编辑
As it turns out, you actually really can call the jQuery constructorwith a standard array.
But it seems like terrible karma to do so, you can't call 95% of all those jQuery methods, unless you want to crash / corrupt your code.
事实证明,您实际上可以jQuery constructor使用标准数组调用。但这样做似乎是可怕的业力,你不能调用所有这些 jQuery 方法的 95%,除非你想崩溃/损坏你的代码。
回答by OdeToCode
Since comments don't allow pretty code listings ... (do they?):
由于评论不允许漂亮的代码清单......(是吗?):
Animate will work against anything. It's documented as only working against CSS properties, but just to prove a point:
Animate 将适用于任何事物。它被记录为仅适用于 CSS 属性,但只是为了证明一点:
var foo = { x: 10, y: 12 };
$(foo).animate({ x: "+=20", y: "20" }, 1000,
function () { alert(foo.x + ":" + foo.y); });
Will spit out "30:20". Is this useful? Perhaps not in everyday work. :)
会吐出“30:20”。这有用吗?也许不是在日常工作中。:)
The trick with arrays is you'll set the same property across each entry. Example:
使用数组的技巧是您将在每个条目中设置相同的属性。例子:
var foo = [{ x: 10 }, { x: 20 }];
$(foo).animate({ x: "+=30" }, 1000,
function () { alert(this.x); });
Spits out "40" and "50".
吐出“40”和“50”。

