【问题标题】:From array of objects, extract value at certain index --> undefined从对象数组中,提取某个索引处的值 --> 未定义
【发布时间】:2016-11-02 00:50:33
【问题描述】:

我在从对象数组的某个索引中获取值时遇到问题。

数组看起来像这样:

[Object, Object, Object, Object]

当我在 Crome 控制台中打开它们时,它看起来像这样:

问题是我想要来自这个对象之一的uuid 的值。

如果我写 console.log(this.myArray[0].uuid),我会从索引 0 获取 uuid。

但是一旦我写了console.log(this.myArray[index].uuid),其中index 是一个数字,我只会得到undefined

我已经试过了

var test = _.map(this.myArray,"uuid");
console.log(test[index].uuid)

但那只会是我undefined

有人可以帮帮我吗?

【问题讨论】:

  • 我想你想要test[index],在地图之后。 map 方法将uuid 属性返回到新数组中;您将其视为转动对象,每个对象都有一个 uuid 属性。
  • 我刚试过var test = _.map(test[index](this.mycards,"uuid")); console.log(test); 但我只得到swipeToRate.controller.js:189 Uncaught TypeError: Cannot read property '9' of undefined(…)
  • 这是因为test[index](this.mycards,"uuid")test[index] 视为一个函数,试图将this.mycards"uuid" 作为参数传递。好吧,实际上这是另一个问题。这似乎是在抱怨 testundefined

标签: javascript angularjs angular-fullstack


【解决方案1】:

如果你想要这样的索引循环数组

for(var i = 0;i<this.myArray.length;i++){

console.log(this.myArray[i].uuid)
}

【讨论】:

    【解决方案2】:

    我认为您在传递 key_.map 的工作方式是错误的:

    let arr = [
      { index: 4, name: 'Hello' },
      { index: 9, name: 'World' }
    ]
    
    _.map(arr, 'index') // produces [4, 9]
    

    因此,如果您希望访问 index 值,则可以直接从数组本身进行。

    let indexes = _.map(arr, 'index')
    
    indexes[0] // 4
    

    【讨论】:

      【解决方案3】:

      我已经试过了

      var test = _.map(this.mycards,"uuid");
      console.log(test);
      console.log(test[index]);
      

      第一个console.log

      console.log(test);
      

      产生一个包含所有 uuid 的数组:

      ["3c539a73-d569-4512-b558-291164f34529", "b6920edc-77a8-4ac6-8fa3-65c7b05ea556", "9d8afb0c-5268-44a1-b02f-0772357025d0", "4a33b232-7c1d-4ee7-b53c-3615c0fbd7d3", "68888839-a888-4595-9be9-3ec07fe35850", "0ab242ca-e6e1-4497-871e-196c3a05e0ec", "0c311bc6-c396-45a9-865e-19cdc8800bf7", "3add00ad-7371-417a-89ae-e4f0966ab503", "ac503849-5476-4710-9c2e-a514a178c4f5"]
      

      但是有了console.log(test[index]);,结果我又得到了undefined

      问题是,我的方法看起来像这样:

      event(index, eventObject) {
      ...  
      };
      

      index 始终是一个数字,我不知道,因为每次调用方法时它都不同。

      但由于某种原因,当我输入一个数字而不是 index (这也是一个数字)像这样 this.myArray[0].uuid 时,我得到了一个结果。 但是当我更改为 this.myArray[index].uuid 时,我得到了未定义。

      我什至尝试过parseInt(index),但也没有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-08
        • 2022-01-23
        • 2018-01-22
        • 2018-12-21
        • 1970-01-01
        • 2013-02-08
        相关资源
        最近更新 更多