gpt4 book ai didi

javascript - 多次查找数组中相同元素的索引

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:34:20 25 4
gpt4 key购买 nike

我想在同一个数组中找到一个元素的POSITIONS,没有方法,有一个算法...

示例:

var a = [1,2,2,1,4,5,6]
to display positions of 1 : position 0 and 3
to display positions of 2 : position 1 and 2

到目前为止我做了什么:

function count(array,element){
while(element in array){
return array.indexOf(element);
}
}

最佳答案

为了得到所有的位置,你必须在返回之前遍历整个数组

var a = [1,2,2,1,4,5,6]

function count(array,element){
var counts = [];
for (i = 0; i < array.length; i++){
if (array[i] === element) {
counts.push(i);
}
}
return counts;
}

count(a, 1); //returns [0,3]
count(a, 2); //returns [1,2]

关于javascript - 多次查找数组中相同元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27443170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com