JSON返回(对象,对象)

时间:2017-02-11 00:48:55

标签: javascript json

有人可以向我解释为什么下面的代码给出(对象,对象)?   (console.log(dope)给出它应该的东西但是在JSON.stringify和JSON.parse之后它只是说对象,对象)。如果你能告诉我它为什么这样做会很棒。

var nombrememes = document.getElementsByClassName("meme").length;
var memenumber = nombrememes + 1;

var newmeme = prompt('Please paste the link of the meme below!');
memes.push ('placememe'+memenumber+'');

var div = document.createElement('div');
document.body.appendChild(div);
div.id = 'placememe'+memenumber+'';
div.className = 'meme';
div.innerHTML = '<img src="'+newmeme+'" width="700" height="700" alt="" />';


var dope = document.getElementById('placememe'+memenumber+'');
console.log(dope);
localStorage.setItem('dope', JSON.stringify(dope));
var pla = JSON.parse(localStorage.getItem('dope'));
alert(pla);

3 个答案:

答案 0 :(得分:1)

这是因为JSON.parse之后您正在处理JavaScript对象。

IE当你正在做{}.toString()时,你不会回来'{}'你回来[object Object]这是Javascript为对象的字符串表示返回的内容。这就是将Javascript对象转换为JSON所必需JSON.stringify()的原因。

如果您想获取警报的字符串,只需将localStorage中的值保留为字符串表示。

var pla = localStorage.getItem('dope');
alert(pla);

答案 1 :(得分:0)

这不起作用。见this question。您正在尝试将DOM节点序列化为JSON,但这是不可能的。相反,它序列化为一个空对象。您正在尝试alert(...)。当您alert某个对象时,它每次都会包含[Object object]

JSON.stringify / JSON.parse操作与您的问题无关。对任何有效的对象都可以正常工作 - 只是不是DOM节点。

要保存DOM节点的部件,您可以保存单个标量属性。例如,可以保存innerHtml。根据需要添加其他属性。

var o = {
    inner: dope.innerHtml
};

答案 2 :(得分:0)

建议:

如果要打印对象以调试代码,请尝试

console.log(pla)

如果 alert

,请尝试使用此功能

试试这个,它会为你输出缩进的JSON对象

alert(JSON.stringify(pla, null, 4));

好处:

  • 跨平台支持
  • ECMAScript第5版标准化
  • 支持Firefox,Chrome,Safari和IE8。