简体   繁体   English

Javascript子数组

[英]Javascript Sub-Array

I recently ran into the problem where I would like to select multiple elements from an array, to return a sub-array. 我最近遇到了一个问题,我想从一个数组中选择多个元素,以返回一个子数组。 For example, given the array: 例如,给定数组:

a = [1, 5, 1, 6, 2, 3, 7, 8, 3]

And the index array of: 和索引数组:

i = [3, 5, 6]

I want to select all elements in a, who's index appears in i. 我想选择a中的所有元素,谁的索引出现在i中。 So the output in my simple example would be: 因此,在我的简单示例中,输出为:

[6, 3, 7]

I completely realise I could use a for loop over i and construct a new array then use Array.push(a[index (in i)]) to add in each, but I was wondering if there was a clearer/cleaner way to achieve this (possibly using underscore.js, or something similar). 我完全意识到我可以在i上使用for循环并构造一个新数组,然后使用Array.push(a [index(in i)])在每个数组中添加,但是我想知道是否有更清晰/更干净的方法来实现(可能使用underscore.js或类似的东西)。

i.map(function(x) { return a[x]; })
// => [6, 3, 7]

You can try this 你可以试试这个

a = [1, 5, 1, 6, 2, 3, 7, 8, 3];
i = [3,5,6];
var res= [];     //for show result array
for (var n in a){      //loop a[]
 for(var index in i){     //loop i[]
     if(  n == i[index] )     //n is index of a[]
     res.push(a[n]);          //add array if equal n index and i[] value
 }
 }
 alert(res);    // 6,3,7 

You could use map function to achieve your desired result. 您可以使用map功能来实现所需的结果。

var a = [1, 5, 1, 6, 2, 3, 7, 8, 3];

var i = [3, 5, 6];

var mapped = i.map(function(index) { 
    return a[index]; 
});

console.log(mapped);

Here is the working jsfiddle . 这是工作的jsfiddle

However with above example, map not be available in all browsers yet. 但是,在上述示例中, map并非在所有浏览器中都可用。 Here is the quote from documentation of map . 这是map文档的报价。

map was added to the ECMA-262 standard in the 5th edition; 在第5版中将地图添加到ECMA-262标准中; as such it may not be present in all implementations of the standard. 因此,它可能并不存在于该标准的所有实现中。

If your code will be running in old browsers then you will need to add a polyfill . 如果您的代码将在旧的浏览器中运行,则需要添加一个polyfill However there are libraries that give you similar functionality with polyfills for older browsers. 但是,有些库polyfills为旧版浏览器的polyfills提供类似的功能。 Along with map function, underscodejs has tons of other helpful functions. 除了map功能外, underscodejs还有许多其他有用的功能。 I higly recommend you to look at what underscorejs has to offer. 我强烈建议您查看underscorejs提供的功能。 It provides tons of helper functions and has quite wide range browser support. 它提供了大量的助手功能,并具有相当广泛的浏览器支持。

You would do following in underscorejs and wont have to worry if your code works in cross browsers. 您可以在underscorejs执行以下操作,并且不必担心代码是否可以在跨浏览器中工作。

var a = [1, 5, 1, 6, 2, 3, 7, 8, 3];

var mapped = _.map([3, 5, 6], function(index) {
    return a[index];
});

alert(mapped);

Here is jsfiddle for that. 这是jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM