简体   繁体   English

有人可以解释 Javascript 中的.indexOf() 的逻辑吗?

[英]Can somebody explain the logic of .indexOf() in Javascript?

function vowelsAndConsonants(s) {
    var vowels = ['a','e','i','o','u'];

    for(let i =0; i<s.length; i++){
        if(vowels.indexOf(s[i]) > -1 ){
            console.log(s[i]);
        }
    }

    for(let j = 0; j<s.length; j++){
      if(vowels.indexOf(s[j]) < 0){
          console.log(s[j]);
      }
    }
}

The code above prints out the vowels and then consonants of an input.上面的代码打印出输入的元音和辅音。

I have troubles understanding how .indexOf() specifically works in this case.我很难理解.indexOf()在这种情况下的具体工作原理。

I understand that .indexOf() searches array and returns the position of an element you're looking for, but why does the following condition if(vowels.indexOf(s[i]) > -1) only returns vowels?我知道.indexOf()搜索数组并返回您要查找的元素的 position,但为什么以下条件if(vowels.indexOf(s[i]) > -1)只返回元音?

  • To my understanding if .indexOf() returns -1 it means that no match was found.据我了解,如果.indexOf()返回 -1,则表示未找到匹配项。 In the case, would if(vowels.indexOf(s[i]) > -1) mean that if a match is found we should execute the code, since it is greater than -1?在这种情况下, if(vowels.indexOf(s[i]) > -1)是否意味着如果找到匹配项,我们应该执行代码,因为它大于 -1?
  • Again, in that case if(vowels.indexOf(s[j]) < 0) would then mean that if a match is not found execute whatever is inside the if statement.同样,在这种情况下if(vowels.indexOf(s[j]) < 0)将意味着如果找不到匹配项,则执行 if 语句中的任何内容。

Could somebody kindly explain the logic and give a simple example?有人可以解释一下逻辑并举一个简单的例子吗? I think I'm getting the logic, but at the same time I think I'm not.我想我明白了逻辑,但同时我认为我没有。

indexOf function searches in the array of vowels. indexOf function 在元音数组中搜索。

If it finds a value it will return it's index, so the result will be greater than -1.如果它找到一个值,它将返回它的索引,因此结果将大于 -1。

And if it doesn't find it, the result will be -1.如果它没有找到它,结果将是-1。

But it's better to use但最好使用
if(vowels.indexOf(s[j]) === -1) instead of if(vowels.indexOf(s[j]) === -1)而不是
if(vowels.indexOf(s[j]) < 0)

Unless you also actually need to know an indexOf result in order to do something with it, in modern JS it is preferable to use .includes() rather than testing against -1 or 0.除非您实际上还需要知道 indexOf 结果才能对其进行处理,否则在现代 JS 中,最好使用.includes()而不是针对 -1 或 0 进行测试。

.includes() is simply more legible .includes()更易读

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

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