[英]Javascript Sub-Array
我最近遇到了一個問題,我想從一個數組中選擇多個元素,以返回一個子數組。 例如,給定數組:
a = [1, 5, 1, 6, 2, 3, 7, 8, 3]
和索引數組:
i = [3, 5, 6]
我想選擇a中的所有元素,誰的索引出現在i中。 因此,在我的簡單示例中,輸出為:
[6, 3, 7]
我完全意識到我可以在i上使用for循環並構造一個新數組,然后使用Array.push(a [index(in i)])在每個數組中添加,但是我想知道是否有更清晰/更干凈的方法來實現(可能使用underscore.js或類似的東西)。
i.map(function(x) { return a[x]; })
// => [6, 3, 7]
你可以試試這個
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
您可以使用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);
這是工作的jsfiddle 。
但是,在上述示例中, map
並非在所有瀏覽器中都可用。 這是map
文檔的報價。
在第5版中將地圖添加到
ECMA-262
標准中; 因此,它可能並不存在於該標准的所有實現中。
如果您的代碼將在舊的瀏覽器中運行,則需要添加一個polyfill
。 但是,有些庫polyfills
為舊版瀏覽器的polyfills
提供類似的功能。 除了map
功能外, underscodejs還有許多其他有用的功能。 我強烈建議您查看underscorejs
提供的功能。 它提供了大量的助手功能,並具有相當廣泛的瀏覽器支持。
您可以在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);
這是jsfiddle 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.