Javascript语法功能问题

时间:2016-01-27 21:17:24

标签: javascript function

为什么以下代码不能将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
}

1 个答案:

答案 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),使用此方法的字符串值不受影响。