gpt4 book ai didi

javascript - 填写 addFullName 函数的代码

转载 作者:行者123 更新时间:2023-11-30 14:03:49 26 4
gpt4 key购买 nike

基本对象问题我似乎无法全神贯注。我确定我想多了。填写 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com