【问题标题】:JS how to add a price to an object and pass it by an argumentJS如何为对象添加价格并通过参数传递
【发布时间】:2019-05-20 09:34:39
【问题描述】:

我是编码新手,已经收到过这个问题,但我不确定如何更正它。有人有什么建议吗?

参数产品将是一个如下所示的对象:

  { type: 'Tofu slices' }

向该对象添加一个价格属性,并将其值设置为作为参数传入的价格。然后返回对象。

这是我想出的答案;

function addPriceToProduct (product, price) {
product.price = price
return product.price
}

我的回答与此相反;

describe("addPriceToProduct", () => {
it("adds a price property to the passed product set to the passed price", () => {
  const product = {
    type: "Tofu slices"
  };
  let newProduct = addPriceToProduct(product, 1.25);
  expect(newProduct).to.eql({ type: "Tofu slices", price: 1.25 });
  newProduct = addPriceToProduct(product, 1.35);
  expect(newProduct).to.eql({ type: "Tofu slices", price: 1.35 });
});
});

【问题讨论】:

    标签: javascript object properties arguments price


    【解决方案1】:

    只返回 product(对象)而不是 product.price(price 属性的值)

    function addPriceToProduct (product, price) {
        product.price = price;
        return product;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2016-01-07
      • 2011-05-22
      • 1970-01-01
      • 2022-08-17
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多