在控制台中查找对象属性.语法的问题
Looking up an object property within the console. Syntax issue
我正在使用对象编写比较函数。我知道,如果我有以下对象- 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;
}
}
相关文章:
- Onclick不会启动..可能存在javascript语法问题
- 基本对象/原型语法问题
- JQuery代码语法问题?(“不允许内联控制结构”)
- Javascript函数变量传递语法问题
- Jison 语法问题,生成解析器出现奇怪错误
- 使用 jssor 滑块的“空元素的 XML 样式关闭语法”问题
- 代码只是没有执行,可能有语法问题,或者我可能完全错了
- JS语法问题还是使用三个.js三个.循环中的图像加载器
- 反应 - 语法问题
- 语法问题.淘汰赛.用于过滤
- bind()存在奇怪的语法问题
- Javascript For..语法问题
- JavaScript语法问题
- javascript插件中未传递参数,html语法问题
- 数组结构中的字符串出现JSON.parse语法问题
- .createElement('object')和许多params的语法问题
- Javascript语法问题
- 有逻辑或语法问题的for循环
- JS正则表达式到Java,语法问题
- HTML 与内联动态 JavaScript 由 PHP 语法问题编写