[英]access array member of type object in javascript
我一直在嘗試從數組(data_array)訪問數組成員。我的變量data_array是json的一部分,類似於下面的代碼。 下面的代碼不是實際的代碼。 當我嘗試創建React組件時,實際的代碼正在發揮作用。 我可以粘貼完整的React組件,但是它將包含一些不必要的信息。 所以我想我會添加一些模擬的例子。 道歉,如果它誤導了人們。 目前,我希望對這種情況下可能出什么問題獲得一些提示? :
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.
讓我感到困惑的是我的第一個輸出,因為它說它是一個Array。 所以也許我缺少了一些東西。 任何幫助,將不勝感激。
編輯:這仍然會缺少一個嵌套的React組件,但是在這種情況下將沒有用。 我現在將嵌套組件稱為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;
數組是typeof對象。 它們只是一個帶有一些奇特事物的對象。
以下示例起作用:
var data = {
"name": "Arjun",
"records" : [
{
"value": 3
},
{
"value": 6
},
{
"value":7
}
]
}
var data_array = data.records
console.log(data_array[0]) // Object {value: 3}
當您執行以下操作時,將發生此錯誤:
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
距離您不遠,可以說您僅將此示例存儲在名為jsonData的變量中:
var jsonData = {
data: {
"name": "Arjun",
"records" : [
{
"value": 3
},
{
"value": 6
},
{
"value":7
}
]
}
}
您需要訪問變量> property> nested property,然后像這樣指定索引:
var data_array = jsonData.data;
console.log(data_array.records[0].value)
->應該記錄3
因此問題可能出在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是一個數組。 data.records在一個數組中。 您希望看到什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.