gpt4 book ai didi

Javascript根据键从对象中获取值与其尺寸小于下一个键相比

转载 作者:行者123 更新时间:2023-11-29 19:10:12 25 4
gpt4 key购买 nike

尝试根据包裹的重量计算运费。

我有一个包含给定重量的价格的对象,例如

shippingPrices = {
'economy': {
[weight]: price,
. . .
}
};

然后我想通过传递包裹重量的函数获得正确的运费,例如:

addShippingPrice(700);  // 700 is weight in grams

我试过这样:

shippingPrices = {
'economy': {
2000: 7,
5000: 9,
10000: 10,
20000: 15,
30000: 22
}
};

var addShippingPrice = function(weight) {
var price = 0;
for( var maxWeight in shippingPrices.economy) {
maxWeight = parseInt(maxWeight, 10);

console.log(shippingPrices.economy[maxWeight]);

if(weight < maxWeight) {
// return price = shippingPrices.economy[maxWeight];
}
}
console.log('amount', price);
};

addShippingPrice(700);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

在这种情况下,“正确”的运费是 7,如果我调用权重为 8000 的函数 addShippingPrice(8000);,它应该返回 10

我怎样才能做到这一点?另外,如果将 shippingPrices 对象更改为数组会更好,我会更改它!

最佳答案

你可以使用一个可迭代的结构,比如

var shippingPrices = {
economy: [
{ weight: 2000, price: 7 },
{ weight: 5000, price: 9 },
{ weight: 10000, price: 10 },
{ weight: 20000, price: 15 },
{ weight: 30000, price: 22 }
],
priority: [
{ weight: 2000, price: 9 },
{ weight: 5000, price: 11 },
{ weight: 10000, price: 12 },
{ weight: 20000, price: 18 },
{ weight: 30000, price: 25 }
]
};

function getShippingPrice(type, weight) {
var price;
shippingPrices[type].some(function (a) {
if (a.weight >= weight) {
price = a.price;
return true;
}
});
return price;
}

var shippingPrices = { economy: [{ weight: 2000, price: 7 }, { weight: 5000, price: 9 }, { weight: 10000, price: 10 }, { weight: 20000, price: 15 }, { weight: 30000, price: 22 }], priority: [{ weight: 2000, price: 9 }, { weight: 5000, price: 11 }, { weight: 10000, price: 12 }, { weight: 20000, price: 18 }, { weight: 30000, price: 25 }] };

console.log(getShippingPrice('economy', 700));
console.log(getShippingPrice('economy', 8000));

ES6

function getShippingPrice(type, weight) {
return (shippingPrices[type].find(a => a.weight >= weight) || {}).price;
}

var shippingPrices = { economy: [{ weight: 2000, price: 7 }, { weight: 5000, price: 9 }, { weight: 10000, price: 10 }, { weight: 20000, price: 15 }, { weight: 30000, price: 22 }], priority: [{ weight: 2000, price: 9 }, { weight: 5000, price: 11 }, { weight: 10000, price: 12 }, { weight: 20000, price: 18 }, { weight: 30000, price: 25 }] };

console.log(getShippingPrice('economy', 700));
console.log(getShippingPrice('economy', 8000));

关于Javascript根据键从对象中获取值与其尺寸小于下一个键相比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39545198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com