jQuery - 为什么它会提醒不需要的东西

jQuery - Why does it alert unwanted things?

本文关键字:不需要 为什么 jQuery      更新时间:2023-09-26

请参阅jsfiddle - http://jsfiddle.net/gr7pa2yz/中的代码

var obj = {
x: 4,
y: 2,
z: {
    z1: {
        z11: "who",
        z12: 44
    }
},
zx: [3, 4, "string"],
zy: undefined
}
iterate(obj);
function iterate(obj) {
$.each(obj, function (i, e) {
    if (typeof e == "object") iterate(e);
    alert(e);
});
}

我的问题 - 你会看到上面的代码正在提醒 3 件事,这些事情无法理解。它提醒 - [对象对象] 两次和 3,4,字符串。怎么来了?

这两个对象是

  • { z11: "who", z12: 44 }
  • { z1: { z11: "who", z12: 44 } }

您会看到"[object Object]" alert调用对象的toString方法:

Object.prototype.toString(); // "[object Object]"

由于数组[3, 4, "string"],您也会"3,4,string"

数组也是对象,但Object.prototype.toStringArray.prototype.toString 覆盖,它调用 join

[3, 4, "string"].join(); // "3,4,string"

您正在迭代对象并为对象的每个属性调用alert。因此,您还会提醒对象zz1自身(而不是其内容),从而导致[Object object]

你想要这样的东西吗?

$.each(obj, function(i, e) {
  if (typeof e == 'object') {
    iterate(e);
  } else {
    alert(e);
  }
}

它向你展示了[object Object],因为当面对一个对象时,你的代码首先这样做:

if (typeof e == "object") iterate(e);

。但是这样做后,它这样做了:

alert(e);

后一点是给你[object Object]警报的原因。

如果您的目标是呼叫iterate而不是呼叫alert

if (typeof e == "object") iterate(e);
else alert(e);

或者,这个更容易调试的版本:

if (typeof e == "object") {
    iterate(e);
}
else {
    alert(e);
}

旁注:typeof null "object";现在,null s会破坏你的迭代函数。