我可以使用一些帮助在一个对象上循环并获得两种产品之间的价格差异。例如,大铁锤和小铁锤的价格有何不同?
这是我到目前为止的
var myarray = [{product: "big hammer", price: 32},{product: "small hammer", price: 22},{product: "wrench", price: 15},{product: "saw", price: 55}];
getPriceDifference(myarray[0].product);
function getPriceDifference(currentProduct){
if(currentProduct === "Big Hammer"){
//do something...this is where I am stuck
}
}
提前致谢。
阵列阵列有多种方法
myarray.map(item => {
})
myarray.foreach(item => {
})
或者,如果您将数据的结构更改为以下内容,则不必烦恼。
var products = {
"big hammer": { price: 32 },
"small hammer": { price: 22 },
"wrench": { price: 15 },
"saw": { price: 55 },
};
function getPriceDifference(product_1, product_2) {
return Math.abs(products[product_1].price - products[product_2].price);
}
var difference = getPriceDifference("big hammer", "small hammer");
console.log(difference);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句