在控制台中查找对象属性.语法的问题

Looking up an object property within the console. Syntax issue

本文关键字:语法 问题 属性 对象 控制台 查找      更新时间:2023-09-26

我正在使用对象编写比较函数。我知道,如果我有以下对象- 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;
}

上面写着"比较未定义与未定义"。见解吗?

代码中的

el["x"]不指向任何东西。el对象中没有带有"x"键的属性

你在for循环中定义了x所以你需要使用这个变量而不是"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;
            }
}