【问题标题】:Strings from index in array - Javascript [duplicate]数组中索引的字符串 - Javascript [重复]
【发布时间】:2018-09-06 16:34:21
【问题描述】:

如果我有一个字符串数组:

array1 = ['mango', 'orange', 'apple','strawberry'];

还有一组索引:

array2 = [1,3];

如何根据 array2 中的索引,用 array1 中的字符串创建一个新数组?

在这种情况下,新数组将如下所示:

array3 = [orange, strawberry]

【问题讨论】:

  • 迭代索引数组并使用这些索引的值来索引第一个数组并将这些值推送到新数组中,请参阅答案/
  • 将 array2 与 array1 映射。尝试一下并尝试添加到您的问题中。
  • 简单的map:const array3 = array2.map((index) => array1[index])

标签: javascript arrays indexing


【解决方案1】:
//Declare a new array object
let newArray = [];

//iterate the array of index values, and use the value to index the first array and push into new array
for(let i = 0; i < array2.length; i++){
    newArray.push(array1[array2[i]]);
}

//log the results in new array
console.log(newArray);

【讨论】:

    猜你喜欢
    • 2012-05-06
    • 2020-01-12
    • 2014-03-02
    • 2019-10-12
    • 2015-07-12
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多