为避免将变量名用作文字,请使用方括号。以下是代码-
var name = "David" var putTheAllData = [] putTheAllData.push( { name: "The name is name will remain same" } ) putTheAllData.push( { [name]: "The name is David will be changed [name]"} ) console.log(putTheAllData);
要运行上述程序,您需要使用以下命令-
node fileName.js.
输出结果
在这里,我的文件名为demo166.js。这将产生以下输出-
PS C:\Users\Amit\javascript-code> node demo166.js [ { name: 'The name is name will remain same' }, { David: 'The name is David will be changed [name]' } ]