gpt4 book ai didi

javascript - 获取数组中所有出现的元素的索引(索引)

转载 作者:行者123 更新时间:2023-11-28 11:35:37 32 4
gpt4 key购买 nike

我有一个数组。例如,[1,2,3,4,1,2,3,4]。如何在不改变数组的情况下获得第一个“3”和第二个“3”的位置?我意识到这是一个类似的问题: Javascript - Get position of the element of the array ,但我想找到两个“3”的位置。有谁知道如何做到这一点? (没有 jQuery)

最佳答案

下面是一个通用函数,它返回数组中指定元素的所有出现位置:

代码:

Array.prototype.indicesOf = function(query) {
var indices = [];
var x = this.indexOf(query);
while(x != -1) {
indices.push(x);
x = this.indexOf(query, x + 1);
}
return indices;
};

用法:

var myArray = [1, 2, 3, 4, 1, 2, 3, 4];
var positions = myArray.indicesOf(3); // `positions` is now [2, 6]

另一个例子:

var thingsTheySaid = ["Hello", "Hi", "Greetings", "Howdy",
"Good morning", "Hello"];

console.log(thingsTheySaid.indicesOf("Hello")); // Logs [0, 5]

关于javascript - 获取数组中所有出现的元素的索引(索引),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22311544/

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