[英]get array value by index jquery
I have an javascript array that has the following values, 我有一个具有以下值的javascript数组,
let arr = ["2","3","4","5","6"];
I have a second array that has three integers, 我有另一个包含三个整数的数组,
let index = [1,3,4];
How would I use JQuery (or Javascript) to use the array to get the index from arr, and add it to a new array. 我将如何使用JQuery(或Javascript)使用数组从arr获取索引,并将其添加到新数组。 I want to add these strings to a new array.
我想将这些字符串添加到新数组中。
indexArr = ["3","5","6"]
Thanks 谢谢
Simple, just use Array.prototype.map()
: 简单,只需使用
Array.prototype.map()
:
let arr = ["2","3","4","5","6"]; let index = [1,3,4]; let indexArr = index.map(i => arr[i]); console.log(indexArr);
You can do it with simple .map 您可以使用简单的.map完成
let arr = ["2","3","4","5","6"];
let index = [1,3,4];
index.map(x=>arr[x]) //["3", "5", "6"]
Just use a loop. 只需使用一个循环。 Personally I prefer this method over
map
because I find this easier to understand, but it's personal preference. 就个人而言,我更喜欢这种方法而不是
map
因为我发现这种方法更容易理解,但这是个人喜好。
let arr = ["2","3","4","5","6"]; let index = [1,3,4]; let indexArr = []; for(var i=0; i<index.length; i++) { indexArr.push(arr[index[i]]); } console.log(indexArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.