【问题标题】:push as object, or as separated items作为对象推送,或作为单独的项目推送
【发布时间】:2021-11-07 12:05:41
【问题描述】:

我有一个非常简单的问题。

但有什么区别:

export const addToCart = function(product, quantity){
    cart.push({product, quantity});
    console.log(`${quantity} ${product} are added`);
}

和

export const addToCart = function(product, quantity){
    cart.push(product, quantity);
    console.log(`${quantity} ${product} are added`);
}

谢谢

【问题讨论】:

  • console.log(cart) 查看差异

标签: javascript arrays typescript ecmascript-6


【解决方案1】:

在这种情况下:

cart.push({product, quantity})

等于

cart.push({ product: product, quantity: quantity})

这个Shorthand property names 是在ES2015/es6 中介绍的。 当有属性名与变量名(包含你的属性值的变量)相同时,初始化对象时不需要提及属性名。

因此,在您的情况下,您将具有属性 property 和 quantity 的对象添加到 cart 数组中。 所以当你控制台日志时,你会看到[{'property': 'bottle', 'quantity': 99 }]

在这种情况下:

cart.push(product, quantity);

您通常添加两个项目,其值在 product 和 quantity 变量中。所以当你控制台日志时,你会看到类似['bottle', 99 ]

cart = [];
//cart = [];
const addToCart = function(product, quantity){
    cart.push({product, quantity});
    console.log(cart);
}

const addToCart2 = function(product, quantity){
    cart.push(product, quantity);
    console.log(cart);
}

addToCart("product 1", 100); // [ { "product": "product 1", "quantity": 100 }]
//addToCart2("product 1", 100); // [  "product 1", 100 ]

【讨论】:

    【解决方案2】:

    首先是将一个对象推入一个数组,而第二个是将每个项目推入一个数组。

    var a =[];
    a.push({b:1,c:2}) // [{b: 1, c: 2}]
    a.push(1,2) // [1,2]
    

    【讨论】:

    • 好吧,但是这样做有什么好处呢?如果你把它当成一个对象来推?
    • 由于您的数据结构是一个字符串字段和一个整数字段,因此建议将其作为对象推送。然后您可以通过许多功能来操作它,例如按名称过滤。
    猜你喜欢
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2022-01-23
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    相关资源
    最近更新 更多