【问题标题】:Looking up an object property within the console. Syntax issue在控制台中查找对象属性。语法问题
【发布时间】:2015-10-12 13:22:54
【问题描述】:

我正在使用对象编写比较函数。我知道如果我有以下对象 - var obj{ one: "foo", two: bar"} 并且我想查找一个属性,那么 obj["one"] 将工作但 obj[one] 不会。

但是,当我执行比较函数时,它会正确比较 obj["one"] 和 obj2["one"],但是当我尝试在控制台中记录它时,语法 obj[one] 有效,而 obj[ "one"] 返回为未定义。它不会影响代码的功能,但我很困惑。

var num = 2;
var num2 = 4;
var num3 = 4;
var num4 = 9;
var num5 = "4";
var obj = {here: {is: "an"}, object: 2};
var obj2 = {here: {is: "an"}, object: 2};

function deepEqual(el, el2) {
  var outcome = false;
  console.log("comparing " + el + " and " + el2);
  if (typeof el == 'object' && typeof el2 == 'object') {
    console.log("These are both objects");
    if (Object.keys(el).length === Object.keys(el2).length) {
      console.log("These objects have the same number of keys");
      for (var x in el) {
        if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
          console.log("comparing " + el[x] + " with " + el2[x]);
          outcome = true;
        } else {
          return false;
        }

      }
    } else return false;
  } else if (el === el2) {
    outcome = true;
  }

  return outcome;
}

所以我说的代码部分是

if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
  console.log("comparing " + el[x] + " with " + el2[x]);
  outcome = true;
} else {
  return false;
}

这在控制台中正确返回为“比较(属性)与(属性)”。但是,如果我这样写

if (el2.hasOwnProperty(x) && el["x"] === el2["x"]) {
  console.log("comparing " + el["x"] + " with " + el2["x"]);
  outcome = true;
} else {
  return false;
}

它说“比较未定义和未定义”。 有什么见解吗?

【问题讨论】:

    标签: javascript object syntax console.log


    【解决方案1】:

    在您的代码中 el["x"] 没有引用任何内容。 el 对象中没有具有“x”键的属性

    您处于定义 x 的 for 循环中,因此您需要使用该变量而不是“x”

    for (var x in el) {
    
                if (el2.hasOwnProperty(x) && el[x] === el2[x]) {
                    console.log("comparing " + el[x] + " with " + el2[x]);
                    outcome = true;
                } else {
                    return false;
                }
    
    }
    

    【讨论】:

    • 你是对的。我不知道为什么,但在它使用 if 语句中的引号而不是 if 语句中的 console.log 中的引号之前。当我从 if 语句中取出引号时,比较无法正常工作......尽管现在它似乎工作正常。如果这是问题,我不确定为什么它会与 if 语句中的引号一起使用。不过还是谢谢。
    • 不知道是否有助于理解,但如果两者都未定义,el["x"] === el2["x"] 将是真的
    猜你喜欢
    • 2017-10-23
    • 2014-08-17
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2017-10-03
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多