我有 1 個陣列和 1 個集合,集合Indexes和陣列是Names.
索引包含各種數字,這些數字基本上是Names 陣列隨機元素的索引。我想根據索引陣列中的索引過濾名稱陣列,即將名稱陣列的特定元素推送到索引存在于索引陣列中的另一個陣列。
我正在做的是:
const Indexes =[0,1]
const Names=["Test1","Test2","Test3","Test4"]
const filteredNames = Indexes.map(item => Names[item]);
輸出應該是:
filteredNames=["Test1","Test2"]
但它不作業。有任何線索嗎?
uj5u.com熱心網友回復:
你幾乎猜對了
const Indexes =[0,1]
const Names=["Test1","Test2","Test3","Test4"]
const filteredNames = Indexes.map(item => Names[item]);
console.log(filteredNames)
uj5u.com熱心網友回復:
它也適用于 set
const Indexes =new Set([0,2]);
let temp=Array.from(Indexes);
const Names=["Test1","Test2","Test3","Test4"]
const filteredNames = temp.map(item => Names[item]);
console.log(filteredNames)
uj5u.com熱心網友回復:
如果索引是一個集合,那么你只需要Array.from函式:
const Indexes =new Set([0,1])
const Names=["Test1","Test2","Test3","Test4"]
const filteredNames = Array.from(Indexes)
.map(item => Names[item]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324139.html
標籤:javascript 数组
上一篇:C#中隨陣列變化而變化的變數值
