【问题标题】:Reading array from different ways gives me different results从不同的方式读取数组给了我不同的结果
【发布时间】:2019-03-25 06:50:27
【问题描述】:

我尝试使用 redux 来存储我的数据并使用来自全局状态的数据。问题是我不明白为什么第三个 console.log() 不起作用。

const results = this.props.popMovies

/* work */ console.log(this.props.popMovies[0].title)

                                    for (var i = 0; i < this.props.popMovies.length; i++)
/* work */ console.log(this.props.popMovies[i].title);

/* dosen't work */ console.log(...results.title)

如果有人可以向我解释原因,它可以帮助我。 谢谢。

【问题讨论】:

    标签: javascript arrays reactjs redux


    【解决方案1】:

    因为resultsarray 并且没有任何标题属性title。所以你实际上在做

    console.log(...undefined)
    

    首先您可以使用map() 将所有标题排列成数组,然后将其传递给console.log

    console.log(...results.map(x => x.title))
    

    这是使用演示数组的演示。

    const result = [{title:"title1"},{title:"title2"},{title:"title3"}]
    
    console.log(...result.map(x => x.title))

    【讨论】:

      【解决方案2】:

      这是因为访问results 数组的title 属性优先于...results.title 上的展开运算符,这基本上意味着上述代码试图展开不存在的results.title 对象/数组.

      试试这个:

      result.forEach(item => console.log(item.title))
      

      【讨论】:

        【解决方案3】:

        编写console.log(...results.title) 意味着您正在尝试传播result.title,但title 不作为result 的属性存在,而是在结果数组内的对象中

        您需要先检索标题,然后再传播它们。为此,您可以使用带有 map 的扩展语法

        console.log(...results.map(item => item.title));
        

        【讨论】:

          猜你喜欢
          • 2020-01-13
          • 2019-06-15
          • 1970-01-01
          • 2017-10-05
          • 1970-01-01
          • 1970-01-01
          • 2015-09-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多