繁体   English   中英

React-for循环仅返回索引,而不返回整个对象

[英]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.

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