简体   繁体   中英

Javascript syntax function issue

Why does the following code work shouldn't title be set to lowercase causing the second if statement to fail?

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
}

You aren't changing the value of the variable. You can prove it by printing out the value of the variable at each step.

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"
}

According to the docs ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase ), the value of the string using this method is not affected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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