我有以下代码
function myFunction(items) {
// this prints out 11
alert(items.length);
$(items).each(function(i, item) {
// item is undefined for some reason
}
}
Run Code Online (Sandbox Code Playgroud)
我提醒物品的长度,它有元素(确切地说是11).那么11个项目怎么可能存在,但jQuery仍然通过undefined?
对此的唯一解释是items数组包含未定义的值,即:
items = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];
Run Code Online (Sandbox Code Playgroud)
其他两个答案都是完全错误的.第一个参数each是索引,而不是值,jQuery.fn.each调用jQuery.each.他们之间没有消歧.
听起来你没有传递jQuery wrappet set给你的功能.如果你传递一个array或者object你需要使用jQuery helper function $ .each()之类的
$.each(items, function(index, element){
});
Run Code Online (Sandbox Code Playgroud)
正如我在其他答案中已多次提到的那样,使用.each()或javascripts native 循环遍历数组是不好的做法for..in.
如果您通过arrays使用标准for loop.
编辑
事实证明,你实际上可以jQuery constructor使用标准数组调用它.但这似乎是一个可怕的业力,你不能调用95%的所有jQuery方法,除非你想崩溃/破坏你的代码.
| 归档时间: |
|
| 查看次数: |
20352 次 |
| 最近记录: |