我有一个这样的数组:
peoples = ['dick', 'jane', 'harry', 'debra', 'hank', 'frank' .... ]
还有一个包含这样的键:
keys = [1, 6, 3, 12 .... ]
现在我可以这样写:
var peoplesStripedOfKeyPostions = [];
for(i = 0; i < peoples.length; i++){
for(j = 0; j < keys.length; j++){
if( i !== keys[j]){
peoplesStripedOfKeyPostions.push( peoples[i] );
}
}
}
如果您看不出来,我需要生成一个人员数组,在数组键中定义的某些位置去除人员。我知道必须有一种巧妙而有效的方法来做到这一点,但我当然想不出。 (阵列管理不是我的强项)。
你知道更好的方法吗? (如果我得到多个有效答案,jsperf 将决定获胜者。)
最佳答案
people.filter(function(x,i){return badIndices.indexOf(i)==-1})
如果 badIndices
数组很大,这将变得低效。一个更高效(尽管不那么优雅)的版本是:
var isBadIndex = {};
badIndices.forEach(function(k){isBadIndex[k]=true});
people.filter(function(x,i){return !isBadIndex[i]})
(注意:您不能使用名为 keys
的变量,因为它是内置函数)
关于javascript - 在某些索引处剥离/删除数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12311467/