【问题标题】:Creating an object with a function with arguments使用带参数的函数创建对象
【发布时间】:2017-09-17 09:13:01
【问题描述】:

好的,我不知道我做错了什么,因为它在我看来是正确的,而且我所有的在线研究都证明我是正确的。但这里是代码和说明:

function newCar(make, model) {
    var car = {
      make = "Nissan",
      model = "model",
     };
}

说明是:创建一个 newCar 函数,该函数接受两个参数:品牌和型号。
使用这些参数,创建一个汽车对象,为其提供品牌和型号属性,然后从函数中返回它

【问题讨论】:

  • 你既没有使用参数也没有返回对象
  • 缺少返回语句错误:)
  • 感谢大家(减去 bennygenel)的相关反馈!我想通了。
  • 你为什么不分享答案?
  • 这是有道理的。这是我第一次学习的早期,所以我想他们从那以后变得更好了!谢谢@SJade。

标签: javascript function object


【解决方案1】:

你可以只返回对象,

function newCar(make, model) {
    return {
        make: make,
        model: model,
    };
}

console.log(newCar('BMW', '320ci'));

或使用可实例化的函数与new operator 一起使用。

function Car(make, model) {
    this.make = make;
    this.model = model;
}

console.log(new Car('BMW', '320ci'));

【讨论】:

    【解决方案2】:
     function newCar(make, model) {
      var car = {
      "make" : make,
      "model" : model,
      };
    
     return car;
    }
    

    【讨论】:

    • newCar("Nissan", "Altima");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多