Javascript 在控制台中查找对象属性。语法问题
我正在使用对象编写一个比较函数。我知道,如果我有以下对象-var obj{one:foo,two:bar},并且我想查找一个属性,那么obj[one]可以工作,但是obj[one]不能 但是,当我执行比较函数时,它会正确地比较obj[one]和obj2[one],但当我尝试在控制台中记录它时,语法obj[one]起作用,而obj[one]返回为未定义。它不会影响代码的功能,但我很困惑Javascript 在控制台中查找对象属性。语法问题,javascript,object,syntax,console.log,Javascript,Object,Syntax,Console.log,我正在使用对象编写一个比较函数。我知道,如果我有以下对象-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; v
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键的属性 您处于定义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]将为真