简体   繁体   中英

Can somebody explain an exclamation mark?

    const string = "Hello There";
    const chars ={};

for(let character of string){
  if(!chars[character]){
    chars[character] = 1;
  }else{
    chars[character]++;
  }
}
console.log(chars);

The following code will print the number of unique letters appearing in a string. I know that exclamation mark means "false", but I do not understand what it represents in the following example:

!chars[character]

I have hard time understanding how it characters are compared with other characters since it clearly states char[at a current i]. If somebody could give a much simpler example. I tried debugging it, but couldn't understand as well.

! inverts the truthyness of an expression. Since chars starts out as an empty object, the first time a character is iterated over, it won't exist on a property of the object; it'll be undefined . Eg, for H :

chars[character]
// equivalent to
chars.H
// resolves to
undefined

// putting ! in front of it makes it truthy instead:
!undefined -> true

So if(!chars[character]){ is saying: if this character doesn't exist on the object yet, then execute the following block:

  chars[character] = 1;
} else {
  // The character has already been iterated over;
  // it exists on the object, and the value is a number
  // Increment that number:
  chars[character]++;
}

You can the expression into two parts:

  1. chars[character] returns undefined or the count of characters in the string as a number
  2. ! (Logical (NOT) operator) coerces the next thing to a boolean and then flips the boolean

Therefore the two possible cases:

chars[character] // undefined
Boolean(chars[character]) // false
!chars[character] // true
chars[character] // 1
Boolean(chars[character]) // true (numbers other than 0 are coerced to true)
!chars[character] // false

More info at MDN

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