当我运行此代码时,浏览器中的结果与节点中的结果不同
const users = [
{
id: 1,
name: "ada",
surname: "wong",
games: [
{ id: 1, name: "g1" },
{ id: 2, name: "g2" },
],
},
{
id: 2,
name: "leon",
surname: "kennedy",
games: [{ id: 2, name: "g2" }],
},
];
const output = users.map((user) => ({ ...user }));
console.log(output);
在浏览器中,我可以看到预期的结果
[
{
"id": 1,
"name": "ada",
"surname": "wong",
"games": [
{
"id": 1,
"name": "g1"
},
{
"id": 2,
"name": "g2"
}
]
},
{
"id": 2,
"name": "leon",
"surname": "kennedy",
"games": [
{
"id": 2,
"name": "g2"
}
]
}
]
但是当我用节点运行它时,我得到这个结果
$node app.js
输出
[
{
id: 1,
name: 'ada',
surname: 'wong',
games: [ [Object], [Object] ]
},
{ id: 2, name: 'leon', surname: 'kennedy', games: [ [Object] ] }
]
我尝试[ [Object], [Object] ]
通过以下方式纠正节点中的此行为,但是尝试所有这些操作后,它们都返回相同的结果
const output = users.map((user) => ({ ...user, games: user.games }));
const output = users.map((user) => ({ ...user, games: [...user.games] }));
const output = users.map((user) => ({
...user,
games: user.games.map(({ id, name }) => ({ id, name })),
}));
为什么在浏览器中与在节点中相比,在另一个对象中进行销毁的对象的输出不同?如何在节点中修复?
这是关于浏览器和终端上的字符串和对象的,最初,浏览器将所有内容都转换为字符串,或者如果您想深度登录nodejs,则可以将其转换为日志中的对象,您可以同时使用两种方式
第一路
// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });
第二种方式
// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句