【问题标题】:What is the proper way to get an element from an array with array destructuring? [duplicate]从具有数组解构的数组中获取元素的正确方法是什么? [复制]
【发布时间】:2019-05-25 11:28:39
【问题描述】:

几乎所有内容都在标题中,但我会给你一个例子:

// i can't know the content of this string but for the exemple she's here
let str = 'elem-0, elem-1, elem-2, elem-3';

// how to properly write this line because this line is not write in an array 'destructuring way'
let array = str.split(',')[0];

// return me : "elem-0" (and he has to)
console.log(array);

【问题讨论】:

  • let [array] = str.split(',');
  • 取决于你想要达到的目标

标签: javascript arrays destructuring


【解决方案1】:

你可以像这样解构数组元素

let [first, second, ...rest] = str.split(',');

基本上它是按索引工作的,第一个变量是 arr[0],第二个是 arr1,依此类推。 ...rest 将保留数组中未解构的剩余项目

查看MDN documentation for Array Destructuring

【讨论】:

  • 您应该避免回答重复详细回答问题的问题(根据您的个人资料,我看到您经常这样做)。您至少应该花时间选择和链接重复项。如果问题被一次又一次地回答,就会有成千上万个简短而回答不好的问题,而回答好的问题将会丢失。
猜你喜欢
  • 2011-03-30
  • 2011-05-15
  • 2012-06-05
  • 2019-09-01
  • 2010-11-26
  • 1970-01-01
  • 2015-06-16
  • 2011-01-15
  • 1970-01-01
相关资源
最近更新 更多