【问题标题】:Get n Value from Javascript Array从 Javascript 数组中获取 n 个值
【发布时间】:2015-09-13 01:28:45
【问题描述】:

我正在尝试遍历 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
});

我应该对我的代码应用哪些更改?

【问题讨论】:

  • 去掉那些 '[1]' ,因为 entry 已经是数组的一个元素了;)

标签: javascript asp.net arrays json


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    .forEach 中的函数可以接受一个索引和一个元素 -

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

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

    【讨论】:

      【解决方案3】:

      如果你不需要使用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);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-01
        • 1970-01-01
        • 2016-09-27
        • 1970-01-01
        • 2018-11-15
        • 1970-01-01
        • 2015-07-02
        • 2020-11-03
        相关资源
        最近更新 更多