Shr*_*pta 5 javascript arrays indexof
我在重复某些值的数组中使用一组数值。我想找到所有重复值出现的索引。
例如,我使用以下代码indexOf():
var dataset = [2,2,4,2,6,4,7,8];
return dataset.indexOf(2);
Run Code Online (Sandbox Code Playgroud)
但这仅给出了第一次出现的索引2。(即它返回值0。)
但是,我希望2返回所有出现的索引(即0,1,3)。我怎样才能做到这一点?(我知道我可以使用for循环,但我想知道是否有更好的方法来做到这一点,而无需遍历整个数组。基本上,我试图节省显式遍历整个数组的开销。)
@Bagavatu:如果你不想 for 循环,你可以尝试这个小提琴-
var dataset = [2,2,4,2,6,4,7,8];
var results = [];
var ind
// the while loop stops when there are no more found
while( ( ind = dataset.indexOf( 2 ) ) != -1 ){
results.push( ind + results.length )
dataset.splice( ind, 1 )
}
return results;
Run Code Online (Sandbox Code Playgroud)
注意:使用 for 循环会快得多。看评论。
var dataset = [2,2,4,2,6,4,7,8];
var results = [];
for ( i=0; i < dataset.length; i++ ){
if ( dataset[i] == 2 ){
results.push( i );
}
}
return results;
Run Code Online (Sandbox Code Playgroud)