[英]React - for loop only returns index and not whole object
我有一個組件,其狀態為以下對象(“項目”):
items:
count: 2
next: null
previous: null
results: Array[2]
0: {…}
id: 1
price: "100.00"
show_in_shop: true
tax_percentage: "5.0000000"
title: 'Object title'
type: "assessment"
1: {…}
id: 2
price: "1000.00"
show_in_shop: true
tax_percentage:"8.0000000"
title: "Title of this object"
type: "class"
我正在創建一個過濾器,它循環遍歷this.state.items.results並檢查Item對象的值是否在搜索查詢中。
但是,運行此代碼時,我遇到了以下問題:
for (let item in this.state.items.results) {
console.log(item);
打印到控制台的是
0
1
並不是:
0: {…}
id: 1
price: "100.00"
show_in_shop: true
tax_percentage: "5.0000000"
title: 'Object title'
type: "assessment"
1: {…}
id: 2
price: "1000.00"
show_in_shop: true
tax_percentage:"8.0000000"
title: "Title of this object"
type: "class"
但為什么? 當我檢查react-chrome插件中的狀態時,我看到'item.results'填充了數據,並且包含的數據多於要打印到控制台的數據。 有誰知道為什么循環只循環遍歷索引而不返回對象?
for .. in
javascript實際上僅返回索引。
采用:
for (let key in this.state.items.results) {
let item = this.state.items.results[key];
console.log(item);
}
this.state.items.result.forEach(item => console.log(item));
for ... in將僅給出索引,如果您想要每個對象,則使用for ... of 。
像這樣:
var arr = [{a:1}, {a:2}]; for(let el of arr){ console.log(el); }
對於循環,您還可以根據需要使用#array.forEach或#array.map 。
用for-of
for (let item of this.state.items.results) {
console.log(item);
}
for ... in將返回集合的索引,而不是集合的項目。 例如:
var array = [10,20,30];
for(var item in array){
console.log(array[item]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.