【问题标题】:jQuery push and each doesn't seem to work?jQuery push 并且每个似乎都不起作用?
【发布时间】:2014-11-16 22:59:11
【问题描述】:

我在 jQuery 中推送到一个数组,之后我无法在该数组上执行 .each,这是什么原因造成的?

Fiddle

var sections = [];
for (var j = 0; j < 15; j++) {
  sections.push("tests-" + j);
}

console.log(sections);  // this is a proper array

sections.each(function(){
  console.log("test");  // Uncaught TypeError: undefined is not a function
});

【问题讨论】:

    标签: jquery push each


    【解决方案1】:

    没有Array.prototype.each 方法,要么使用Array.prototype.forEach 要么使用jQuery $.each 实用函数。您尝试使用的 each 方法属于 jQuery 对象,用于遍历集合。您可以使用 $(sections).each(fn) 语法从数组创建 jQuery 对象并使用它的 each 方法,但这是一个坏主意,应该避免,因为 sections 不是 DOM 元素数组。

    请注意,jQuery 有 2 个each 方法,一个是utility function,另一个是a method of jQuery object

    当您将 jQuery 方法定义为 this 时,您可以使用 this.each,因为 context 指的是 jQuery 对象,它是一个类似数组的对象,即它具有一些 Array 方法但它不是一个真正的数组,它是一个jQuery对象,你可以在jQuery对象上调用.get()方法来获取内部数组,现在返回的数组有.forEach()方法但没有.each()方法。

    sections.forEach( function(elem) { console.log(elem); });
    $.each(sections, function(index, elem) { console.log(elem); }); 
    

    【讨论】:

    • 这真的很令人困惑,因为我正在使用 this.each 上面几行,它似乎在那里工作:stackoverflow.com/questions/26962363/… - 你能解释一下为什么它在那里工作并且不会在这种情况?因为第一个是 DOM 元素,而这里只是一个 JS 数组?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    相关资源
    最近更新 更多