javascript - 填写 addFullName 函数的代码

标签 javascript function object methods

基本对象问题我似乎无法全神贯注。我确定我想多了。 填写 addFullName 函数的代码。该函数应该:

Take one input parameter, a person object. Add a property called fullName to the person object when called. The new fullName property is set to the string 'firstName lastName' (one string, with a space between the two names) Modify the object passed in without returning anything.

// an example `person` object
var person = {
    firstName: 'Joseph',
    lastName: 'Magnolia',
    ageInYears: 34
}

function addFullName(personObj) {
  /* your code here */
  person.fullName = personObj.firstName + ' ' + personObj.lastName;
}

测试结果:

✗ it should set fullName property to 'Joseph Magnolia'
  Error:
    fullName does not equal 'Joseph Magnolia': expected undefined to deeply equal 'Joseph Magnolia'
✗ it should set fullName property to 'Michael Smith'
  Error:
    fullName does not equal 'Michael Smith': expected undefined to deeply equal 'Michael Smith'

最佳答案

您的代码非常接近,您只需使用作为参数传递给函数的变量/对象。该参数称为 personObj,应该在函数内部使用以处理传递给函数的任何 Person 对象。

// an example `person` object
var person = {
    firstName: 'Joseph',
    lastName: 'Magnolia',
    ageInYears: 34
}

function addFullName(personObj) {
  // You want to use the variable/object passed to the function
  personObj.fullName = personObj.firstName + ' ' + personObj.lastName;
}

addFullName(person);
alert('Joseph Magnolia' === person.fullName);

ES6 改进

如果你使用 ES6,你可以使用模板字符串:

function addFullName(personObj) {
  // You want to use the variable/object passed to the function
  personObj.fullName = `${personObj.firstName} ${personObj.lastName}`;
}

关于javascript - 填写 addFullName 函数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55841548/

相关文章:

javascript - 如何使内容仅可编辑列表?

javascript - 调用回调方法

javascript - 在 JavaScript 中递增多维数组

jquery - 命名 jQuery 函数

java |找不到符号 |返回一个对象

java - 设置接口(interface)问题和对象

php - 如何动态更改页眉和页脚?

c - 无法删除结构中的确定位置,数据仍然存在

c - 如何将数组包含到 C 函数定义中

java - java中对象的依赖关系