Javascript jQuery:正确循环对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4603574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:13:24  来源:igfitidea点击:

jQuery: Looping through object properly?

javascriptjqueryloopsobjecteach

提问by Industrial

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.

我正在尝试使用以下代码片段遍历下面显示的 JS 对象,同时需要获取索引键和内部对象。

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"])

回答by Nick Craver

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

您正在获取的内部对象valueObj数组,它只是没有方法.toSource()(至少不是跨浏览器),如果您删除它,您将收到警报:

$.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:

....toString()数组的默认值是一个逗号分隔的列表,所以这就是您在alert(). 例如,如果您改为执行alert(key + "/" + valueObj[0] );,您会看到:

prop_1/1
prop_2/3

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

...所以你可以看到你确实有你想要的数组,你可以在这里测试

回答by Steve

You could use a for in loop:

您可以使用 for in 循环:

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