【问题标题】:Why If statement returns undefined for hashTable?为什么如果语句返回未定义的哈希表?
【发布时间】:2017-10-26 06:07:10
【问题描述】:

谁能解释一下这个 JavaScript 怪癖?

一个例子:

function func(hashTable) {
  if (hashTable['foo'])
    return true;
}

var hash = {};
hash['foo'] = 0;
func(hash);

我得到undefined 而不是true

【问题讨论】:

  • (hashTable['foo']) 在其值为 0 时评估为 false,因此跳过 return true。然后返回 undefined。
  • @KaisinLi ,您希望 if 块在什么条件下执行?
  • @RohitAgrawal 最初我试图检查 hashTable 是否有键 'foo'。但正如您所建议的,hasOwnProperty 是更好的选择。

标签: javascript algorithm data-structures hashtable


【解决方案1】:

那是因为你 returned 函数针对单一覆盖情况(当hastTable['foo'] 为真时)。

hashTable['foo']0if(0) 被解释为 false 并且您没有 returned 在这种情况下的值。

JavaScript 中,不仅是 JavaScript,我们还有所谓的 falsy values。它们分别是:0nullundefinedfalse""NaN

【讨论】:

  • 啊,我明白了,我错过了“if(0) 被解释为错误部分”。谢谢!
【解决方案2】:

hashTable['foo'] 的值为 0,其计算结果为布尔值 false。因此if 块永远不会被执行。

如果您想在 hashTable 具有属性 foo(或任何其他属性)时执行 if 块,而不管其值如何,您可以这样做:

function func (hashTable) {
  return hashTable.hasOwnProperty("foo");
}

var hash = {}
hash['foo'] = 0;
console.log(func (hash));

【讨论】:

  • 这个答案缺少一些重要的东西。你可以return hashTable.hasOwnProperty("foo");,根本不需要if语句
  • 谢谢@Jonasw。只是忘记了。更新了我的答案
【解决方案3】:

也许更短更好:

const func = table => "foo" in table;

哈希表应该这样构造:

const hash = Object.create(null);

因为 ES 6 有更好的构造来处理这些事情:

const hash = new Map();
//to check
hash.has("foo")

【讨论】:

  • Map 的问题是如果 'foo' 的值为 0,hash['foo'] 会返回 undefined
  • @kaisin 因为它的hash.get("foo")
【解决方案4】:

要检查对象是否包含特定属性,请使用in.hasOwnProperty()

如果属性存在于对象上或其原型链上的任何位置,in 将生成 true 值。

.hasOwnProperty() 返回 true 如果该属性存在于对象本身(原型未检查)。

function Student(name) {
  this.name = name;
}
 
Student.prototype.occupation = 'student';

var john = new Student('John');

// in
console.log('name' in john);        // true
console.log('occupation' in john);  // true
console.log('age' in john);         // false

// .hasOwnProperty()
console.log(john.hasOwnProperty('name'));       // true
console.log(john.hasOwnProperty('occupation')); // false
console.log(john.hasOwnProperty('age'));        // false

【讨论】:

    【解决方案5】:

    只有当 hashTable['foo'] 为真时才会返回 Becz;

    hashTable['foo'] 为 false,因为您已分配 0;

    所以... 函数函数(哈希表){ 如果(哈希表['foo']){ 返回真 }别的{ 返回假 } }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      相关资源
      最近更新 更多