繁体   English   中英

js对象和if语句。 为什么此代码在没有else且不使用else或else if语句的情况下有效?

[英]js objects and if statements. why this code works without an else and using an else or else if statement doesn't?

我是一个非常入门的JS“开发人员”(学生),我遇到一个我无法解决的问题:当我不使用else语句时,为什么“ helperHash”中重复字母的值会增加为什么使用else语句时相同的值不会增加? 我的代码按预期运行,但是我在理解此问题背后的逻辑时遇到了问题。

该代码应返回一个数组,该数组的字母在给定的str中具有1个或多个重复。

function nonUniqueLetters(str){
  var strToChars = str.split('');
  var finalArr = [];
  var helperHash = {};
  for (let i = 0; i < strToChars.length; i += 1){
    let char = str[i];
    if (!helperHash[char]){
      helperHash[char] = 0;
    }
    helperHash[char] += 1;  //HERE! why doesn't this work if inside an else?
  }
  for (var key in helperHash){
    if (helperHash[key] > 1){
      finalArr.push(key);
    }
  }
  return finalArr;
}

对于helperHash[char]

初始值为undefined!undefinedtrue因此将其设置为0

下次char具有相同的值时, helperHash[char]0!0 也为 true因此它将值设置为0 (该值已经是,因此没有区别)。


代替测试该值是否为假值,可以测试它是否未定义或是否存在。

if (typeof helperHash[char] === "undefined")

要么

if (char in helperHash) 

原因是这样的if (!helperHash[char]){以及如何在Javascript中将整数转换为布尔值。

您将哈希的每个成员都初始化为0,这等于布尔值false,因此绝不会命中else,因为helperHash[char] === 0 === false ,因此!helperHash[char]对于所有以0初始化的值都是true

逻辑错误。

当前代码的工作方式:

if (!helperHash[char]){
    // Enters here only when helperHash[char] is not set (or 0, but it is never 0)
    helperHash[char] = 0;
}
// Always increment
helperHash[char] += 1;
// There is no 0 in helperHash at this point

为什么将helperHash[char] += 1放在else分支中不起作用:

if (!helperHash[char]){
    // Enters here only when helperHash[char] is not set or 0
    helperHash[char] = 0;
    // Still 0, will take this branch again on the next occurrence of char
} else {
   // Increment only if it was already 1 or more (this never happens)
   helperHash[char] += 1;
}
// Here helperHash contains only 0 for all keys

如何运作:

if (!helperHash[char]){
    // This is the first occurrence of char, let's count it
    helperHash[char] = 1;
} else {
    // This is a subsequent occurrence of char, let's count it too
    helperHash[char] += 1;
}
// There is no 0 in helperHash at this point

您的if条件:

!helperHash[char]

总是评估为truehelperHash永远不会包含“虚假”字符)。 因此, if永远不会被击中, if该分支的else分支。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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