我正在用 Nodejs 编写一个 CLI 应用程序。用户看到一个项目列表并选择一个他们想要删除的项目。他们看到的列表是通过 JSON 文件生成的。JSON 文件有一个属性,其中包含一系列操作:
{
"actionList":[
"Action 1","Action 2","Action 3","Action 5","Action 6"]
}
他们的输入触发要删除的项目和要使用更新列表重写的文件fs.writeFileSync
。
当我写入文件 WITHOUT{}
时,它将数组写入没有属性的 JSON 文件actionList
:
代码:
fs.writeFileSync(
path.join(__dirname, "./.todo.json"),
JSON.stringify( actionList , null, 4)
);
结果:
["Action 1","Action 2","Action 3","Action 5","Action 6"]
但是当我在 actionList 周围使用 {} 时,我会得到带有actionList
属性的 JSON 文件。
代码:
fs.writeFileSync(
path.join(__dirname, "./.todo.json"),
JSON.stringify({ actionList }, null, 4)
);
结果:
"actionList":[
"Action 2","Action 3","Action 5","Action 6"]
}
在这种情况下,{} 到底在做什么?
{ actionList }
是相同的{ "actionList": actionList }
它是 ES6 属性的简写。
另一个例子:https ://alligator.io/js/object-property-shorthand-es6/
因此,{}
在您的对象周围添加了另一层,带有一个键"actionList"
和变量的值actionList
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句