有人可以解释 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]);
}
}
}
上面的代码打印出输入的元音和辅音。
我很难理解.indexOf()
在这种情况下的具体工作方式。
我明白 .indexOf()
搜索数组和 returns 你要查找的元素的位置,但为什么以下条件 if(vowels.indexOf(s[i]) > -1)
只有 returns 元音?
- 据我了解,如果
.indexOf()
returns -1 表示没有
找到匹配项。在这种情况下, if(vowels.indexOf(s[i]) > -1)
意味着如果找到匹配我们应该执行代码,因为它大于 -1?
- 同样,在那种情况下
if(vowels.indexOf(s[j]) < 0)
将意味着
如果找不到匹配项,则执行 if 中的任何内容
声明。
谁能解释一下逻辑并举个简单的例子?我想我明白了逻辑,但同时我又觉得我没有。
indexOf
函数在元音数组中搜索。
如果它找到一个值,它将 return 它是索引,因此结果将大于 -1。
如果没有找到,结果将为-1。
不过最好用
if(vowels.indexOf(s[j]) === -1)
而不是
if(vowels.indexOf(s[j]) < 0)
除非您实际上还需要知道 indexOf 结果才能对其执行某些操作,否则在现代 JS 中,最好使用 .includes()
而不是针对 -1 或 0 进行测试。
.includes()
更易读
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]);
}
}
}
上面的代码打印出输入的元音和辅音。
我很难理解.indexOf()
在这种情况下的具体工作方式。
我明白 .indexOf()
搜索数组和 returns 你要查找的元素的位置,但为什么以下条件 if(vowels.indexOf(s[i]) > -1)
只有 returns 元音?
- 据我了解,如果
.indexOf()
returns -1 表示没有 找到匹配项。在这种情况下,if(vowels.indexOf(s[i]) > -1)
意味着如果找到匹配我们应该执行代码,因为它大于 -1? - 同样,在那种情况下
if(vowels.indexOf(s[j]) < 0)
将意味着 如果找不到匹配项,则执行 if 中的任何内容 声明。
谁能解释一下逻辑并举个简单的例子?我想我明白了逻辑,但同时我又觉得我没有。
indexOf
函数在元音数组中搜索。
如果它找到一个值,它将 return 它是索引,因此结果将大于 -1。
如果没有找到,结果将为-1。
不过最好用
if(vowels.indexOf(s[j]) === -1)
而不是
if(vowels.indexOf(s[j]) < 0)
除非您实际上还需要知道 indexOf 结果才能对其执行某些操作,否则在现代 JS 中,最好使用 .includes()
而不是针对 -1 或 0 进行测试。
.includes()
更易读