为什么以下代码不能将title设置为小写,导致第二个if语句失败?
var title = 'RANDOM_LETTERS';
if(title.toLowerCase() == 'random_letters')
{
//This will fire
}
if(title == 'RANDOM_LETTERS')
{
//This will still fire as the variable was not saved to lowercase
}
答案 0 :(得分:3)
您没有更改变量的值。您可以通过在每一步打印出变量的值来证明它。
var title = 'RANDOM_LETTERS';
console.log(title);
// Here, title is "RANDOM_LETTERS"
if(title.toLowerCase() == 'random_letters')
{
console.log(title);
// Here, title is still "RANDOM_LETTERS"
}
console.log(title);
// Here, title is "RANDOM_LETTERS"
if(title == 'RANDOM_LETTERS')
{
//We get to this line, our title is still "RANDOM_LETTERS"
}
根据文档(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase),使用此方法的字符串值不受影响。