有人能解释一下感叹号吗?

Rom*_*Kim 3 javascript 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);
Run Code Online (Sandbox Code Playgroud)

以下代码将打印出现在字符串中的唯一字母的数量。我知道感叹号的意思是“假”,但我不明白它在下面的例子中代表什么:

!chars[character]
Run Code Online (Sandbox Code Playgroud)

我很难理解如何将它的字符与其他字符进行比较,因为它清楚地说明了 char[at a current i]。如果有人可以举一个更简单的例子。我尝试调试它,但也无法理解。

Cer*_*nce 5

! 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
Run Code Online (Sandbox Code Playgroud)

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]++;
}
Run Code Online (Sandbox Code Playgroud)