繁体   English   中英

如何获取数组 n 中元素 m 的最后一次出现

[英]how to get last occurance of element m in array n

我刚开始编程,我只是想访问数组 n 中元素 m 的最后一个 position。下面给出的代码提供了元素 m 的所有位置。

 var n = [];
        while (true) {
            let input = prompt("enter number to array");
            if (input == null || input == "c") {
                break;
            }
            n.push(Number(input));
            console.log(n);
        }
        var m = prompt("enter number to be match");
        console.log(m)
        for (var i = 0; i < n.length; i++) {
            if (n[i] == m) {
                console.log(i);
            } 

}

您可以使用内置的Array.prototype.lastIndexOf() function 来获取最后一个索引。

.lastIndexOf()方法返回可以在数组中找到给定元素的最后一个索引,如果不存在,则返回 -1。 这个 function 以相反的顺序搜索数组,即从数组的最后一个索引到第一个索引。

n.lastIndexOf(m);

 var n = []; while (true) { let input = prompt("enter number to array"); if (input == null || input == "c") { break; } n.push(Number(input)); } var m = Number(prompt("enter number to be match")); console.log(n.lastIndexOf(m));

您可以在相反的方向上迭代数组 - 请注意构造for循环的新方式:

var n = [];
while (true) {
    let input = prompt("enter number to array");
    if (input == null || input == "c") {
        break;
    }
    n.push(Number(input));
    console.log(n);
}
var m = prompt("enter number to be match");
console.log(m)
for (var i = n.length - 1; i >= 0; i--) {
    if (n[i] == m) {
        console.log(i);
    } 
}

笔记:

虽然我的解决方案展示了如何改变您现有的方法以达到预期的结果,但请注意Yousaf 的解决方案是一个更简洁的实现; 如果您想编写简洁的代码,那么我建议您利用这种方法。

欢迎来到编程社区:)

这实际上很容易。 您可以使用Array.prototype.lastIndexOf()来检索元素最后出现的索引。

我必须补充一点,您可能应该检查错误情况,例如,如果用户输入的内容不是 integer。 但为简单起见,我将仅粘贴您要查找的内容,而无需进行错误检查

let n = [];

while (true) {
  const input = prompt('enter number to array');
  if (!input || input === 'c') {
    break;
  } else {
    n.push(Number(input));
    console.log(n);
  }
}

const m = Number(prompt('enter number to be match'));
console.log(m);
const lastIndexOfElement = n.lastIndexOf(m);
if (lastIndexOfElement < 0) {
  console.log(`element ${m} could not be found`);
} else {
  console.log(
    `the last occurence of ${m} can be found at position ${lastIndexOfElement}`
  );
}

您可以使用n.indexOf(m) ( https://www.w3schools.com/jsref/jsref_indexof.asp ) 来获取索引 (i)。 请注意, indexof 可以为负数,如果为负数,则它不在数组中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM