美好的一天,我目前正在寻找一种方法来查找任何数组中值的所有索引。该值可能在该数组中出现多次。我可以使用.includes
和.indexOf
来找到第一个位置,类似于
function indexOfValue(needle, hayStack) {
if(hayStack.includes(needle)) {
return hayStack.indexOf(needle);
}
}
console.log(indexOfValue(12, [12, 1, 3, 3, 6, 12]));
但这个log
只有针的第一个位置的value
。
这就是我试图获得所有index
function indexOfValue(needle, hayStack) {
let result = [];
for(let i = 0; i < hayStack.length; i++) {
if (hayStack.includes(needle)) {
return result.push(hayStack[i]);
}
return result;
}
}
console.log(indexOfValue(12, [12, 1, 3, 3, 6, 12]));
但上面的代码由于某种原因返回1
而不是[0,5]
。请问这个特定代码的问题是什么,我该如何修复它?
返回result.push
会缩短你的迭代次数,甚至不包括索引。而是检查每个元素是否等于针,然后推送索引,如果它相等。
function indexOfValue(needle, hayStack) {
let result = [];
for(let i = 0; i < hayStack.length; i++) {
if (hayStack[i] === needle) { // check if matching
result.push(i); //push the index
}
} return result; //return result at end
}
console.log(indexOfValue(12, [12, 1, 3, 3, 6, 12]))
你的代码的问题是你的回归太早了。
每次从函数中return
时,退出该函数,停止其余代码在其中执行/运行。
因此,正如你在for循环中使用return
ing一样,你正在阻止你的循环进行任何其他检查。这意味着你应该在循环完成后返回。
此外,您还需要在for循环中修复if
语句。目前您正在检查传入的数组(hayStack
)是否包含您要查找的项目(needle
)。相反,你需要检查当前项目(使用haystack[i]
)是否是needle
,然后如果你需要将i
(这是当前索引)推入你的result
数组。
见下面的工作示例:
function indexOfValue(needle, hayStack) {
let result = [];
for(let i = 0; i < hayStack.length; i++) { // loop through the array, where `i` is the current index in the array
if (hayStack[i] === needle) { // check if a given number inthe array is the `needle`, if it is:
result.push(i); // add the index of the item to the result array
}
}
return result; // only once the loop is complete return the array
}
console.log(indexOfValue(12, [12, 1, 3, 3, 6, 12]));
如果您愿意,您还可以使用reduce
等高阶函数来完成相同的任务:
const indexOfValue = (n, arr, i) =>
arr.reduce((acc, num, i) => num === n ? [...acc, i] : acc, [])
console.log(indexOfValue(12, [12, 1, 3, 3, 6, 12]));
在return
循环中for
s问题的两个代码示例。第二个例子qazxswpo是.push()
数组的元素,而不是result
。
您可以使用index
的第二个参数来设置索引以开始搜索,检查.indexOf()
的结果是否大于.indexOf()
且索引不在-1
数组中,result
return
数组在result
循环之后
for
function indexOfValue(needle, hayStack) {
let result = [];
for(let i = 0; i < hayStack.length; i++) {
let index = hayStack.indexOf(needle, i);
if (index > -1 && result.indexOf(index) === -1) {
result.push(index);
}
}
return result;
}
console.log(indexOfValue(12, [12, 1, 3, 3, 6, 12]));
遍历整个数组并为数字索引创建一个数组。如下
const numbers = [11, 3, 6, 8, 11];
const indexOfValue = (val,numbers) =>{
let filtered =[];
numbers.filter((number,index) => {
if(val === number)
filtered = [...filtered,index];
})
return filtered;
}
console.log(indexOfValue(11,numbers));