jQuery: Looping through object properly?

谁说我不能喝 提交于 2019-12-04 16:56:58

问题


I am trying to loop through the below shown JS object with the following code snippet, while needing to fetch both the index key as well as the inner object.

How on earth should I do this, as the following doesn't work?

The object:

({ prop_1:["1", "2"],
 prop_2:["3", "4"]})

My code:

$.each(myObject, function(key,valueObj){
    alert(key + "/" + valueObj.toSource() );
});

Expected output:

prop_1 / (["1", "2"])

回答1:


The inner object you're fetching fine, valueObj is the array, it just has no method .toSource() (at least not cross-browser anyway), if you remove that you'll get an alert:

$.each(myObject, function(key,valueObj){
    alert(key + "/" + valueObj );
});

You can test it out here, don't be thrown that the output is just:

prop_1/1,2
prop_2/3,4

...the default .toString() on an Array is a comma delimited list, so that's what you see with an alert(). For example, if you instead did alert(key + "/" + valueObj[0] );, you'd see:

prop_1/1
prop_2/3

...so you can see you do have the Array you want, you can test that here.




回答2:


You could use a for in loop:

    var myObject = ({ prop_1:["1", "2"], prop_2:["3", "4"]})
    for (var key in myObject) {
       if (myObject.hasOwnProperty(key)) {
           alert(key + "/" + myObject[key]);
        }
     }


来源:https://stackoverflow.com/questions/4603574/jquery-looping-through-object-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!