【问题标题】:Javascript using an indexOf() inside for loopJavascript 在 for 循环中使用 indexOf()
【发布时间】:2019-12-18 16:11:23
【问题描述】:

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) {

  const x = newArray.indexOf([i])
  console.log(x)
}

我是 javascript 的初学者,我不明白为什么这段代码不起作用。 我试图以最简单的方式产生这个结果:

0:4
1:-1
2:-1
3:-1
4:-1
5:-1 

相反,它遍历数组并产生 6 x -1。即使数组中的第一个元素确实再次出现。 感谢您在理解为什么会发生这种情况以及如何解决它方面提供的任何帮助

【问题讨论】:

  • 为什么要将索引放在数组中?即使它不在数组中,0 也应该返回 -1,因为它无论如何都不在数组中
  • 您应该改用newArray[i]。不过,我不确定你为什么要这样做。它只会返回第一个实例的索引
  • 我不知道['t', 'r', 'c', 'g', 't', 'h'] 应该如何以0:4, 1:-1, 2:-1, 3:-1, 4:-1, 5:-1 结尾
  • 我不明白为什么人们回答一个没有明确结果的问题。
  • @Kobe 他给出了输入和输出,这是产生该输出的唯一合乎逻辑的方式,虽然我同意,但问题应该更简洁。我的代码确实产生了结果(实际上,只需将其复制粘贴到您的控制台中......)

标签: javascript arrays for-loop indexof


【解决方案1】:

据我了解,您想在数组序列中找到重复项的第一个以下位置。

原答案

这可以通过findIndex 来完成,它需要一个回调来确定索引是否算作找到。在这里你可以指定item需要等于并且索引需要大于你当前的索引,因此它是一个重复的item。

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) { 
   // Find the index of the first item which index is greater than the current item and the latter equals the item
   const x = newArray
      .findIndex((item, index) => index > i && newArray[i] === item);

   console.log(`${i}: ${x}`);
}

更好的解决方案

正如 cmets 中提到的(感谢 T.J. Crowder),indexOf 将第二个参数作为开始搜索的偏移量。这是首选的解决方案,因为它更快、更简洁。

let newArray = ['t', 'r', 'c', 'g', 't', 'h'];

for (let i = 0; i < newArray.length; i++) { 
   const x = newArray.indexOf(newArray[i], i+1); 
   console.log(`${i}: ${x}`);
}

【讨论】:

  • FWIW,findIndex 在这里是错误的工具,尽管它会起作用。 如果这是 OP 想要做的,他们应该只使用 indexOf 的第二个参数:const x = newArray.indexOf(newArray[i], i + 1);
  • @T.J.Crowder 你是对的,老实说,不知道indexOf 有第二个参数。我会改变这个。不过,findIndex 仍然有效,如果它比平等更复杂,它将是正确的工具。
  • :-) 是的,就像您可以用扳手敲钉子一样,但用锤子敲钉子要简单得多。很好的编辑!
  • 感谢@pascalpuetz。感谢您抽出宝贵时间回答
  • @chs242 不客气!如果这是您需要的,您能否将答案标记为正确?干杯!
【解决方案2】:

在上面的代码中,indexOf 在数组中搜索 i 的位置,但没有找到,因为数组元素都不是数字。

试试:

const x = newArray.indexOf(newArray[i])

【讨论】:

    【解决方案3】:

    问题是indexOf([i])中的[i]只是一个数组,里面有一个数字。

    如果你有indexOf(newArray[i]),那么你至少会得到答案 [0, 1, 2, 3, 0, 5] (角色会找到自己,除了第二个 t 找到第一个 @987654324 @ 在位置 0)。

    但我假设您只想知道即将到来的字母的位置,而不是之前的位置。

    你可以做的是从数组的末尾循环,将每个字母保存在一个对象中,如果字母已经存在,则替换它。

    我会将代码添加到方法中,以便更容易与其他数组一起使用。

    function findOccurancies(newArray) {
      let newObj = {};
      let currentCharacter = '';
      let x = [];
    
      for (let i = newArray.length-1; i >= 0; i--) {
         currentCharacter = newArray[i];
    
         if (newObj.hasOwnProperty(currentCharacter)) {         
           x.unshift(newObj[currentCharacter]) // place the item first.
         } else {
           x.unshift(-1)                       // place the item first.
         }      
    
         newObj[currentCharacter] = i;
      }
      
      return x;
    }
    
    console.log(findOccurancies(['t', 'r', 'c', 'g', 't', 'h']));
    
    console.log(findOccurancies(['t', 'r', 'c', 'g', 't', 'h', 't']));

    【讨论】:

      【解决方案4】:

      没看懂,如果只想打印数组,需要直接上位置:

      let newArray = ['t', 'r', 'c', 'g', 't', 'h'];
      
      for (let i = 0; i < newArray.length; i++) {
      
        const x = newArray[i]
        console.log(x)
      }
      

      如果你想打印数组中每个值的位置,可以这样做:

      let newArray = ['t', 'r', 'c', 'g', 't', 'h'];
      
      for (let i = 0; i < newArray.length; i++) {
      
        const x = newArray.indexOf(newArray[i])
        console.log(x)
      }
      

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-14
        • 1970-01-01
        相关资源
        最近更新 更多