【问题标题】:How to print a return statement from an Object in JavaScript?如何从 JavaScript 中的对象打印返回语句?
【发布时间】:2022-08-16 02:10:06
【问题描述】:

所以我试图让我的代码打印出一条返回“这是来自美国的鲍勃·马丁”的消息。

这就是我到目前为止所做的。我一直试图弄清楚出了什么问题,但似乎无法使其正常工作。我提供了 cmets 来指导我的思维过程


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

}
  • console.log(printBio())
  • 似乎您拨打了 printBio();返回后的函数内部,这不起作用
  • 代码编辑器按钮是您的朋友[<>],它打开了一个充满可能性的世界,比如清晰的代码。

标签: javascript object composite complex-data-types


【解决方案1】:

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

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);
};

【讨论】:

    【解决方案2】:

    如果对象已经定义,你应该将它定位到你的函数中:

    function printBio(user) {
      return `This is ${user.name} ${user.surname} from ${user.address.country}.`
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 2021-02-06
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多