比较运算符 !== 与 0

Comparison operators !== against 0

本文关键字:运算符 比较      更新时间:2023-09-26

我认为我的代码的作用是显而易见的。

如果我使用 !== 运算符,为什么我的代码会返回整个字符串?我知道 Javascript 中的数组从索引 0 开始,在这里我输入整个文件名作为参数,所以indexOf(".")总是大于 0 .不,我不会在这里传递 .htaccess 文件。

function getFileExtension(i) {
    // return the file extension (with no period) if it has one, otherwise false
   if(i.indexOf(".") !== 0) { // 
       return i.slice(i.indexOf(".") + 1, i.length);
   } else {
       return false;
   }
}
// here we go! Given a filename in a string (like 'test.jpg'),
getFileExtension('pictureofmepdf'); return given string
// both operand are same type and value

但是如果我将比较更改为

(i.indexOf(".") > 0) // logs false 

附言我的情况是你在问,这是表格usvsth3m。

indexOf()返回子字符串的索引,因此它可以返回 0 ,这意味着子字符串出现在位置 0 。如果未找到子字符串,它将返回-1,因此请更改if语句以反映此逻辑:

if(i.indexOf(".") >= 0)

此外,您应该使用 substring() 从字符串中提取子字符串 - slice() 用于数组。

return i.substring(i.indexOf(".") + 1, i.length);

不过,我认为更好的方法是使用 split()

var fileNameArray = i.split("."); // "foo.txt" --> ["foo" "txt"]
if(fileNameArray.length >= 2) {
    return fileNameArray[1];
} else {
    return false; //maybe you want to return "" instead?
}

String 方法indexOf返回(如果成立)您搜索的字符串的第一个索引,请记住,index 可以为零,这就是为什么您必须进行严格的比较以检查它是否indexOf没有返回布尔值 false

在这种情况下,我建议您使用 lastIndexOf,因为名为 something.min.js 的文件将返回 min.js 作为有效扩展名,不。

好吧,为了简化起见,我省略了 indexOf 返回数字类型或 -1索引,在找不到给定值的情况下不返回布尔值 FALSE。因此,在比较 -1 和 0 的情况下,结果为真,这就是为什么我实际上输出给定字符串而不是 false。好吧,MDN 现在在我的书签栏中

var z = -1;
console.log(z >= 0); // evaluates false because -1 < 0
console.log(z !== 0); // evaluates true because -1 !== 0
// also if z > 0 it is !== 0, but could be < 0 

所以下一个代码就像一个魅力。

function getFileExtension(i) {
    // i will be a string, but it may not have a file extension.
    // return the file extension (with no period) if it has one, otherwise false
   if(i.indexOf(".") >= 0) {
       return i.substring(i.indexOf(".") + 1, i.length);
   } else {
       return false;
   }
}
getFileExtension('pictureofmepdf');