jquery $.each() 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6208052/
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-26 20:32:47  来源:igfitidea点击:

jquery $.each() for objects

jqueryeach

提问by matiasdelgado

<script>
    $(document).ready(function() {
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
        $.each(data.programs[0], function(key,val) {
            alert(key+val);
        });
    });
</script>

This code retrieves the first data. name:zonealarmand price:500.

此代码检索第一个数据。name:zonealarmprice:500

How can I retrieve all the data in the object?

如何检索对象中的所有数据?

I tried $.each(data.programs, function(key,val)but it didn't work.

我试过了,$.each(data.programs, function(key,val)但没有用。

Should I put it in a loop?

我应该把它放在一个循环中吗?

回答by Tomalak

$.each()works for objects and arrays both:

$.each()适用于对象和数组:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});

...and since you will get the current array element as second argument:

...并且由于您将获得当前数组元素作为第二个参数:

$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});

回答by Chandu

You are indeed passing the first data item to the each function.

您确实将第一个数据项传递给 each 函数。

Pass data.programs to the each function instead. Change the code to as below:

将 data.programs 传递给 each 函数。将代码更改为如下:

<script>     
    $(document).ready(function() {         
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };         
        $.each(data.programs, function(key,val) {             
            alert(key+val);         
        });     
    }); 
</script> 

回答by Morgan ARR Allen

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

基本上你需要在这里做两个循环。您已经在做的是迭代第 0 个数组元素中的每个元素。

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

你有程序:[ {...}, {...} ] 所以程序 [0] 是 { "name":"zonealarm", "price":"500" } 所以你的循环只是在过去。

You could do an outer loop over the array

你可以在数组上做一个外循环

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}