最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - .each not working on an Array. But .isArray returns true? - Stack Overflow

programmeradmin1浏览0评论

I have created an object which contains a few items, including one which contains multiple objects each of which contains an array. Here is how it is structured.

$.myVar = {
    cp : "",
    ps : {
        m1 : ["001", "002", "003"],
        m2 : ["002", "004"]
    }
};

My scripts keep crashing saying that $.myVar.ps["m1"] has no method each.

When I got into Chrome's console to investigate, I run the following and get the displayed output.

$.myVar.ps["m1"]
["001", "002", "003"]
$.myVar.ps["m1"].each( function (i, p) {alert(i)})
TypeError: Object 001,002,003 has no method 'each'

Also if I run the following, it proves that m1 is an array.

$.isArray($.myVar.ps["m1"])
true

So it seems to agree with m1 is an array, but it refuses to treat it as such. Any idea what I'm doing wrong?

I have created an object which contains a few items, including one which contains multiple objects each of which contains an array. Here is how it is structured.

$.myVar = {
    cp : "",
    ps : {
        m1 : ["001", "002", "003"],
        m2 : ["002", "004"]
    }
};

My scripts keep crashing saying that $.myVar.ps["m1"] has no method each.

When I got into Chrome's console to investigate, I run the following and get the displayed output.

$.myVar.ps["m1"]
["001", "002", "003"]
$.myVar.ps["m1"].each( function (i, p) {alert(i)})
TypeError: Object 001,002,003 has no method 'each'

Also if I run the following, it proves that m1 is an array.

$.isArray($.myVar.ps["m1"])
true

So it seems to agree with m1 is an array, but it refuses to treat it as such. Any idea what I'm doing wrong?

Share Improve this question asked Nov 24, 2010 at 19:03 McBMcB 1,2221 gold badge20 silver badges40 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 19

each is not a native Array method; it is a method of jQuery objects, i.e. those created by the $ function. You can either do

$($.myVar.ps.m1).each(function (i, el) { /* ... */ });

(not recommended, because it creates an unnecessary jQuery object when it wraps the array in $(...)) or you can just use $.each:

$.each($.myVar.ps.m1, function (i, el) { /* ... */ });

The most recommended route, if you are using a modern browser (IE >=9), or using es5-shim, is to use the standard Array.prototype.forEach method:

$.myVar.ps.m1.forEach(function (el, i) { /* ... */ });

Note the different argument order (IMO better since you can then leave out the index if you don't need it).

.each is only defined for jQuery objects. For pure Javascript arrays, use the "static method" $.each.

$.each($.myVar.ps["m1"], function(i,p) { alert(i); });

each is not a method of an array in javascript. try:

$($.myVar.ps["m1"]).each
发布评论

评论列表(0)

  1. 暂无评论