【发布时间】: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