Fre*_*all 4 javascript arrays loops
我有一个这样的数组:
peoples = ['dick', 'jane', 'harry', 'debra', 'hank', 'frank' .... ]
Run Code Online (Sandbox Code Playgroud)
一个包含这样的键:
keys = [1, 6, 3, 12 .... ]
Run Code Online (Sandbox Code Playgroud)
现在我可以这样写:
var peoplesStripedOfKeyPostions = [];
for(i = 0; i < peoples.length; i++){
for(j = 0; j < keys.length; j++){
if( i !== keys[j]){
peoplesStripedOfKeyPostions.push( peoples[i] );
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你不能说,我需要产生一系列在数组键中定义的某些位置被剥夺人员的人.我知道必须有一个漂亮而有效的方法来做到这一点,但我当然无法想到它.(阵列管理不是我的强项).
你知道更好的方法吗?(如果我得到多个工作答案,jsperf确定胜利者.)
people.filter(function(x,i){return badIndices.indexOf(i)==-1})
Run Code Online (Sandbox Code Playgroud)
如果badIndices阵列很大,这将变得效率低下.更高效(尽管不那么优雅)的版本是:
var isBadIndex = {};
badIndices.forEach(function(k){isBadIndex[k]=true});
people.filter(function(x,i){return !isBadIndex[i]})
Run Code Online (Sandbox Code Playgroud)
(注意:你不能使用一个名为变量的变量,keys因为它是一个内置函数)
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |