简体   繁体   English

Javascript - 如何为 object 属性使用变量

[英]Javascript - How using a variable for object property

Im very beginner in javascript, i would like to use all variable created on each object property:我是 javascript 的初学者,我想使用在每个 object 属性上创建的所有变量:

let title = "Les Miserables";
let resume = "Blabla blaaabla...";
let autor = "Victor Hugo"
let date = "1862"

const books = {
        title: title,
        resume: desc,
        autor: autor,
        date: date,
      }

I want a result like this =>我想要这样的结果=>

{ title:'Les Miserables', resume:'Blabla blaaabla...', autor:'Victor Hugo', date: '1862'}

Is this possible?这可能吗?

You can use object property shorthand notation :您可以使用object 属性速记符号

 let title = "Les Miserables"; let resume = "Blabla blaaabla..."; let autor = "Victor Hugo"; let date = "1862"; const books = { title, resume, autor, date, }; console.log(books); /* Logs: { title: "Les Miserables", resume: "Blabla blaaabla...", autor: "Victor Hugo", date: "1862" } */

You can also assign the values directly to properties on the object instead of first declaring individual variables in the scope:您还可以将值直接分配给 object 上的属性,而不是首先在 scope 中声明各个变量:

 const books = {}; books.title = "Les Miserables"; books.resume = "Blabla blaaabla..."; books.autor = "Victor Hugo"; books.date = "1862"; console.log(books); /* Logs: { title: "Les Miserables", resume: "Blabla blaaabla...", autor: "Victor Hugo", date: "1862" } */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用javascript的变量名在数组内添加对象属性? - How to add an object property inside an array using a variable name for javascript? 如何使用变量引用在 Javascript 中修改嵌套 object 的内部属性 - How to modify an inner property of a nested object in Javascript using a variable reference 如何使用变量访问javascript对象的函数属性 - How to access the function property of a javascript object using variable 如何使用JavaScript中的变量动态访问对象属性? - How do I access an object property dynamically using a variable in JavaScript? 使用变量作为javascript对象属性的一部分 - Using a variable as part of a javascript object property 使用变量作为名称向 JavaScript object 添加属性? - Add a property to a JavaScript object using a variable as the name? 如何在JavaScript中将对象的属性获取为变量? - How to get property of an object to a variable in Javascript? 如何将JavaScript变量作为属性存储在对象内部 - How to store a JavaScript variable inside of an object as a property 如何使用包含属性名称的变量从javascript对象中选择属性 - How to select property from object in javascript using a variable containing the property name 使用JavaScript将新属性从变量分配给对象的属性 - Assign new Property to an Object's Property From Variable using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM