jQuery:正确地循环对象? [英] jQuery: Looping through object properly?

查看:85
本文介绍了jQuery:正确地循环对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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


推荐答案

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

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

...默认<数组上的code> .toString()是逗号分隔列表,因此您使用 alert()查看。例如,如果您改为 alert(键+/+ valueObj [0]); ,您会看到:

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

这篇关于jQuery:正确地循环对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆