如何在JavaScript中打印Object的返回语句



所以我正试图让我的代码打印出一条返回"This is Bob Martin from USA"的消息。

到目前为止,我就是这么做的。我一直在试图弄清楚出了什么问题,但似乎无法让它发挥作用。我提供了评论来指导我的思维过程


function printBio(user) {
// function to print message, user is the object and parameter for my function 
// User object that possesses properties as displayed
let user = {
name: 'Bob',
surname: 'Martin',
age: 25,
address: '',
country: "USA"
}
}
return 'This is ' + user.name + ' ' + user.surname + ' from ' + user.country + '.';
// My attempt for a return statement to print my desired message   
printBio();
// The last step, which is to simply have the function do its job and print the message according to the return statement
}

如果您正试图获得一个内置方法来标记您的用户对象:

class User {
constructor(name, surname, age, address, country) {
this.name = name;
this.surname = surname, 
this.age = age;
this.address = address;
this.country = country;
}
printBioMethod() {
const bio = `This is ${this.name} ${this.surname} from ${this.country}.`;
console.log(bio);
}
}

或者,如果您喜欢外部函数来提取对象变量

const printBioFunction = obj => {
const { name, surname, country } = obj;
const bio = `This is ${name} ${surname} from ${country}.`;
console.log(bio);
};
function printBio(user) {
return `This is ${user.name} ${user.surname} from ${user.address.country}.`
}

这是平台给出的解决方案

最新更新