我正在研究Javascript中的.filter()方法。我在网上遇到了这个例子。
var heroes = [
{name: "Batman", franchise: "DC"},
{name: "Ironman", franchise: "Marvel"},
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == "Marvel";
})
document.write(marvelHeroes);
我希望得到一系列仅显示漫威英雄的对象。但是,当我尝试打印marvelHeroes变量的结果时,得到以下结果:
[对象对象],[对象对象]
有人可以告诉我这是怎么回事吗?
答案 0 :(得分:1)
您需要将JS数据结构转换为字符串才能在页面上查看。为此,您使用stringify
。此外,要获得良好的格式化输出,并将字符串添加到具有良好缩进的pre
元素中。
var heroes = [{"name":"Batman","franchise":"DC"},{"name":"Ironman","franchise":"Marvel"},{"name":"Thor","franchise":"Marvel"},{"name":"Superman","franchise":"DC"}];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == "Marvel";
})
const pre = document.querySelector('pre');
pre.textContent = JSON.stringify(marvelHeroes, null, 2);
<pre></pre>
答案 1 :(得分:1)
问题是,您正在向其发送原始JavaScript对象。正如其他人指出的那样,如果对该数组进行字符串化处理,该错误将消失。 [object Object]
出现的原因是浏览器只能将字符串放入HTML。因此,为了将这些对象强制转换为字符串,它使用了Object#toString
方法,这导致每个方法都被转换为[object Object]
的字符串。通过使用JSON.stringify
对对象进行序列化,然后再将其写入文档,可以确保对象以字符串形式正确表示。
const object = { a: 'a', b: '2', c: 3 };
const stringOne = object.toString();
const stringTwo = JSON.stringify(object);
document.write(stringOne);
document.write(stringTwo);
答案 2 :(得分:0)
您尝试编写对象,然后再将其字符串化(转换为json)
document.write(JSON.stringify(marvelHeroes));
var heroes = [
{name: "Batman", franchise: "DC"},
{name: "Ironman", franchise: "Marvel"},
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == "Marvel";
})
document.write(JSON.stringify(marvelHeroes));