繁体   English   中英

从Javascript数组中获取n值

[英]Get n Value from Javascript Array

我正在尝试迭代JavaScript数组并将各个对象值显示为警报。 基本上,数组包含person类型的对象

"person" : {
     "id": String,
     "name": String,
     "address": String
}

我的数组如下:

//This is where I get my array from the code behind. It's not empty. I checked
var obj = JSON.parse(val)

obj.forEach(function (entry) {
    console.log(entry);
    //This prints the entire array and its objects
});

我想要的不是打印整个阵列,我想打印:

obj.forEach(function (entry) {
    console.log(entry[1].name);
    console.log(entry[1].address);
    //This prints the entire array and its objects
});

我应该对代码进行哪些更改?

在foreach中, entry只是一个person元素,使用:

obj.forEach(function (entry) {
        console.log(entry.name);
        console.log(entry.address);
});

.forEach中的函数可以使用索引和元素 -

$.each(obj, function(index, element) {
...
});

所以你可以直接使用元素,也可以使用索引。

如果您不需要使用vanilla JS,则可以使用JQuery:

$( obj ).each(function( index ) {
   console.log($( this ).name);
   console.log($( this ).address);
});

要么

$( obj ).each(function( index ) {
    console.log($( obj )[index].name);
    console.log($( obj )[index].address);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM