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

javascript - $.each Doesn't work for object array in jquery - Stack Overflow

programmeradmin1浏览0评论

i have a array and i need to use each of this items , but forEach and $.each dont work for array here a exmple ( jsfiddle )

var person = new Array();
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
jQuery.each(person, function(index, item) {
    alert(index + " : " + item);
});

i have a array and i need to use each of this items , but forEach and $.each dont work for array here a exmple ( jsfiddle )

var person = new Array();
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
jQuery.each(person, function(index, item) {
    alert(index + " : " + item);
});
Share Improve this question edited Jul 5, 2014 at 3:41 Pointy 414k62 gold badges594 silver badges627 bronze badges asked Jul 5, 2014 at 3:37 PnsadeghyPnsadeghy 1,2892 gold badges13 silver badges20 bronze badges 1
  • I remend to read the MDN JavaScript guide: developer.mozilla/en-US/docs/Web/JavaScript/Guide/… – Felix Kling Commented Jul 5, 2014 at 4:31
Add a ment  | 

4 Answers 4

Reset to default 6

That's an associative array, which is really just an object. To enumerate the key-value pairs of some object obj, use a for-loop:

for (let key in obj) {
    console.log(key, ":", obj[key])
}

That's not an object array; it's an array to which you've added string-named properties. JavaScript is not like PHP - there's a distinct difference between arrays and plain objects.

The $.each() function will detect that you've passed it an array instance, and it will then only look at the numerically-indexed properties. Your string-named properties will be ignored.

Declare your "person" object as a plain object and things will work better:

var person = {};

JavaScript arrays are for numerically-indexed properties. If you want something that maps strings to values, use a plain object.

When you use forEach or $.each() to loop over an array they loop over the numeric indices. Of which you don't have any given that your code is creating properties with string property names. Use an object instead of an array:

var person = {};
// other code as is

You will then be able to use $.each(), because it can handle arrays or plain objects. You won't be able to use the array forEach method because you won't then have an array.

Also your fiddle doesn't work because you didn't include jQuery under the Frameworks & Extensions section at the left. See this updated, working version: http://jsfiddle/4HJ4B/6/

Try this:

var jsonStr = '[{"firstName": "John", "lastName": "Doe", "age": 46},{"firstName": "John-2", "lastName": "Doe-2", "age": 26}]';
var person = $.parseJSON(jsonStr);
$(person).each(function(index, item) {
    console.log(index + " : " + item.firstName);
});
发布评论

评论列表(0)

  1. 暂无评论