[英]How to print a return statement from an Object in JavaScript?
so Im trying to get my code to print out a message that returns 'This is Bob Martin from USA'.所以我试图让我的代码打印出一条返回“这是来自美国的 Bob Martin”的消息。
This is what I did so far.这就是我到目前为止所做的。 I've been trying to figure out what went wrong but can't seem to get this to work.我一直试图弄清楚出了什么问题,但似乎无法让它发挥作用。 I provided comments to guide my thought processes我提供了意见来指导我的思考过程
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
}
If you are trying to get a built in method to tag onto your user object:如果您尝试使用内置方法标记您的用户 object:
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);
}
}
Or If you prefer an external function to pull out the objects variables或者,如果您更喜欢外部 function 来提取对象变量
const printBioFunction = obj => {
const { name, surname, country } = obj;
const bio = `This is ${name} ${surname} from ${country}.`;
console.log(bio);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.