在不使用.indexOf
的情况下,我尝试从末尾循环遍历数组以查找特定值的最后一次出现。这是我到目前为止所拥有的,但它不断返回 undefined
。
var lastIndexOf = function (array, index) {
for (i=array.length-1; i < 0; i--) {
if (array[i] === index) {
return i;
}
}
}
console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1); //should return 3
console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 2); //should return 4
最佳答案
你的检查是错误的,索引的i
永远不会小于零。
顺便说一下,如果你检查一个值,你可以使用名称值而不是index
,这会导致错误的假设并提前声明所有变量。
var lastIndexOf = function(array, value) {
var i;
for (i = array.length - 1; i >= 0; i--) {
if (array[i] === value) {
return i;
}
}
return -1; // standard default value for not found indices
};
console.log(lastIndexOf([0, 1, 4, 1, 2], 1)); // 3
console.log(lastIndexOf([0, 1, 4, 1, 2], 2)); // 4
console.log(lastIndexOf([0, 1, 4, 1, 2], 42)); // -1
使用 while
循环的更短方法。
var lastIndexOf = function(array, value) {
var i = array.length
while (i--) {
if (array[i] === value) {
return i;
}
}
return -1;
};
console.log(lastIndexOf([0, 1, 4, 1, 2], 1)); // 3
console.log(lastIndexOf([0, 1, 4, 1, 2], 2)); // 4
console.log(lastIndexOf([0, 1, 4, 1, 2], 42)); // -1
关于javascript - 查找数组中最后一次出现某个值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129812/