【问题标题】:Get array data in a function在函数中获取数组数据
【发布时间】:2019-11-20 21:49:05
【问题描述】:

我正在尝试提取数组中的数据,但是,我似乎做得不对,但是当我控制台记录它时,我可以看到所有数据。我希望能够只提取数组中的所有标题。请告诉我我哪里弄错了。

      const movies = [
       {
         title: 'Show stopper',
         rate: 5,
         runtime: 120,
         information: 'Show stopper is available',
       },
       {
         title: 'Drive through',
         rate: 233,
         runtime: 65,
         information: 'Drive through is not available',
       },
      ];

        componentDidMount() {
          this.getItemValues();
        }

        getItemValues = () => {
          const { title, rate } = movies;

          console.log(title, rate);
        }

【问题讨论】:

  • 你能分享这段代码的上下文吗?它在类/组件内部吗?
  • 您的movies 变量是一个包含对象的数组。您的解构声明表明您想要获取属性“title”和“rate”的值,但 array 没有这样的属性。数组中的对象可以,但您必须遍历数组并单独对每个对象执行某些操作。

标签: javascript arrays reactjs react-native


【解决方案1】:

Movies 不是一个数组,只是一个带有标题和速率键的对象。您可以使用 for 循环或 forEach 遍历数组的元素。例如:

getItemValues = () => {
  movies.forEach((element) => console.log(element.title, element.rate));
}

这将打印出您的所有标题和费率。您已经接近于做您想做的事了,只要记住您发送到变量和函数中的内容的类型即可。

回答你的问题:你可以

let titles = [];
getItemTitles = () {
   movies.forEach((movie) => titles.push(movie.title);)
}

【讨论】:

    【解决方案2】:

    Pointy 是对的。

    你不能像那样解构数组。

    您需要遍历数组并存储值。

    movies.map(e => {   
        return {
        title: e.title, 
        rate: e.rate 
        }
    })
    

    【讨论】:

      【解决方案3】:

      阅读Array.prototype.map - 这无疑是实现目标的最简单方法:

      const movies = [{
        title: 'Show stopper',
        rate: 5,
        runtime: 120,
        information: 'Show stopper is available',
      }, {
        title: 'Drive through',
        rate: 233,
        runtime: 65,
        information: 'Drive through is not available',
      }];
      
      const titles = movies.map(movie => movie.title);
      
      console.log(titles)

      因此,使用这种方法,您的 React 代码将如下所示:

      componentDidMount() {
          this.getItemValues();
      }
      
      getItemValues = () => {
          const titles = movies.map(movie => movie.title);
          console.log(titles);
      }
      

      仅供参考Object destructuringArray destructuring 虽然相似,但使用不同的语法,应正确使用。在您的代码中,您正在尝试使用对象解构语法来解构数组,这将无法按预期工作)。

      【讨论】:

        【解决方案4】:

        你可以试试这个:

        componentDidMount() {
            const titles = this.getItemValues();
            console.log(titles);
        }
        
        getItemValues = () => movies.map(movie => movie.title);
        

        【讨论】:

          猜你喜欢
          • 2014-12-11
          • 2018-11-22
          • 2021-03-22
          • 2021-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-13
          相关资源
          最近更新 更多