简体   繁体   English

在javascript中访问类型为object的数组成员

[英]access array member of type object in javascript

I have been trying to access array member from an Array (data_array).My variable data_array is part of json something similar to code below. 我一直在尝试从数组(data_array)访问数组成员。我的变量data_array是json的一部分,类似于下面的代码。 The code below is not the actual code. 下面的代码不是实际的代码。 The actual code is coming in play when i am trying to create a React component. 当我尝试创建React组件时,实际的代码正在发挥作用。 I can paste the complete React component but it would contain some unnecessary information. 我可以粘贴完整的React组件,但是它将包含一些不必要的信息。 So i thought i would add some mock example. 所以我想我会添加一些模拟的例子。 Apologies if it misled people. 道歉,如果它误导了人们。 Currently i was hoping to get some hints on what could possibly go wrong in such scenario? 目前,我希望对这种情况下可能出什么问题获得一些提示? :

data: {
    "name": "Arjun",
    "records" : [
      {
        "value": 3
      },
      {
        "value": 6
      },
      {
        "value":7
      }
    ]
  }
   var data_array = data.records

   console.log(data_array) -> Array[3]
   console.log(data_array[0]) -> It displays Uncaught TypeError: Cannot read property '0' of undefined
   console.log(typeof data_array) -> Object. 

What's confusing to me is my first output as it says its an Array.I am fairly new to javascript. 让我感到困惑的是我的第一个输出,因为它说它是一个Array。 So maybe i am missing something. 所以也许我缺少了一些东西。 Any help would be appreciated. 任何帮助,将不胜感激。

Edit: This would still be missing a nested React Component but it would be of no use in this case. 编辑:这仍然会缺少一个嵌套的React组件,但是在这种情况下将没有用。 I am calling the nested component Foo for now 我现在将嵌套组件称为Foo


var React = require('react'),
  Router = require('react-router'),
  mui = require('material-ui'),
  Foo = require('./foo.jsx');


var TempReact = React.createClass({
  mixins: [Router.Navigation],

  getInitialState: function() {
    return {
      data: {}
    };
  },

  componentDidMount: function() {
    // Do a web request here to actually get the data from the backend API
    // this.setState({

    // });

    // For now, load our fake data
    this._loadFakeData();
  },

  render: function() {
    //console.log(this.state.data)
    for(var record in this.state.data.records) {
      console.log(record.Value);
    }
    //console.log(this.state.data["records"][0]["Value"])
    return (
      <div>

        <p>^ That will still say , since the header up there is decided by temp-page.jsx, which is
          based on the route</p>

        <br/>
        <p>We've loaded the fake data into our component's state, and here's proof:</p>
        {this.state.data.name}
        <br/>
        <br/>

        <Foo name={["temp1",this.state.data.records,"green"]}/>

      </div>
    );
  },

  _loadFakeData: function() {
    this.setState({
    data: {
        "name": "Arjun",

        "records" : [
          {
            "Value": 6
          },
          {
            "Value": 7
          },
          {
            "Value": 8
          }
        ]
      }
    });
  }

});

module.exports = TempReact;

Arrays are typeof Object. 数组是typeof对象。 They're just an object with some fancy stuff going on. 它们只是一个带有一些奇特事物的对象。

The following example works: 以下示例起作用:

var data = {
"name": "Arjun",
"records" : [
    {
        "value": 3
    },
    {
        "value": 6
    },
    {
        "value":7
    }
  ]
}
var data_array = data.records
console.log(data_array[0]) // Object {value: 3}

This error happens when you do something like this: 当您执行以下操作时,将发生此错误:

var data = {};
var data_array = data.array; // data.array is undefined and subsequently data_array.
console.log(data_array[0]); // Throws: Uncaught TypeError: Cannot read property '0' of undefined

You're not far off lets say you store this object in a variable called jsonData just for an example : 距离您不远,可以说您仅将此示例存储在名为jsonData的变量中:

var jsonData = {
  data: {
    "name": "Arjun",
    "records" : [
      {
        "value": 3
      },
      {
        "value": 6
      },
      {
        "value":7
      }
    ]
  }

}

You'll need to access the variable > property > nested property , then specify the index like so : 您需要访问变量> property> nested property,然后像这样指定索引:

var data_array = jsonData.data;
   console.log(data_array.records[0].value)

--> should log 3 ->应该记录3

EXAMPLE HERE: http://codepen.io/theConstructor/pen/wGdpjq 此处的示例: http : //codepen.io/theConstructor/pen/wGdpjq

So the problem might have been with SetState() in React, I was able to access the objects by pushing them first in an empty array: 因此问题可能出在React中的SetState()上,我能够通过首先将它们推入一个空数组来访问这些对象:

var varArr = new Array();
for(key in this.state.data.records) {
   if(this.state.data.records.hasOwnProperty(key)) {
       var value = this.state.data.records[key];
       varArr.push(value);
   }
 }

data_array is an Array. data_array是一个数组。 data.records in an Array. data.records在一个数组中。 What are you expecting to see? 您希望看到什么?

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

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