我正在用 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"]
}
在這種情況下,{} 到底在做什么?
uj5u.com熱心網友回復:
{ actionList }是相同的{ "actionList": actionList }
它是 ES6 屬性的簡寫。
參考:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015
另一個例子:https ://alligator.io/js/object-property-shorthand-es6/
因此,{}在您的物件周圍添加了另一層,帶有一個鍵"actionList"和變數的值actionList。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/456176.html
