简体   繁体   中英

how to add a property to an object?

Given an object that has a "firstName" property and a "lastName" property, "addFullNameProperty" returns a "fullName" property whose value is a string with the first name and last name separated by a space.

var person = {
  firstName: 'Jade',
  lastName: 'Smith'
};
addFullNameProperty(person);
console.log(person.fullName); // --> 'Jade Smith'

my code :

function addFullNameProperty(obj) {
  // your code here
  obj[fullName] = obj.firstName + obj.lastName;
}

Either use obj.fullName or obj['fullName']

But a more correct solution would be

 function addFullNameProperty(obj) { // your code here Object.defineProperty(obj, 'fullName', { get: function(){ return this.firstName + ' ' + this.lastName; }, configurable:false }); } var person = { firstName: 'Jade', lastName: 'Smith' }; addFullNameProperty(person); console.log(person.fullName); // --> 'Jade Smith' person.firstName = "Mike"; console.log(person.fullName); // --> 'Mike Smith' 

This way your object will always return the correct fullName .

Just simple set:

obj.fullName instead of  obj[fullName]

Or

obj['fullName']

Because fullName in your code is undefined variable. So JS alert error.

If you want to add the space into the name, you will need to do string interpolation , like so:

`${obj.firstName} ${obj.lastName}`

and complement this with Gaby's answer about switching to dot notation , obj.fullName

Add new property to an existing object:

const person = {
  firstName: 'Jade',
  lastName: 'Smith'
};

person.fullName = `${person.firstName} ${person.lastName}`;

same as:

person['fullName'] = `${person.firstName} ${person.lastName}`;

or using method:

const person = {
    firstName: 'Jade',
    lastName: 'Smith',
    fullName(){ 
        return `${this.firstName} ${this.lastName}`;
    }
};

person.fullName(); // Jade Smith

You can also use defineProperty

Try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM