【发布时间】:2020-05-19 16:16:45
【问题描述】:
首先,我知道有关此问题的多个主题。但我只是找不到它在我的情况下不起作用的原因。
我正在尝试在数组中找到最近的最高值 qty。该数组是动态创建的。
所以在下面的例子中,当前值/数量是17。我想从数组中返回包含qty: 60的对象。
无论我尝试什么输出都是undefined。我就是不明白为什么会这样。
<div class="product" data-url="some-url-to-json" data-quantity="17">
....
</div>
$(function(){
$('#form-pagecart .product').each(function(){
var url = $(this).data('url') + '?format=json';
var cur_qty = $(this).data('quantity')
var highestArray= []
$.getJSON(url, function(data){
$.each(data.product.discounts, function(index, disc) {
highestArray.push({ qty: parseInt(disc.quantity), price: disc.price.price_incl, price_excl: disc.price.price_excl })
});
});
/* things I tried ======> */
var output = highestArray.slice().reverse().find(({ qty }) => qty <= cur_qty);
var nearest = highestArray.sort(function(a, b){
return Math.abs(a.qty - cur_qty) - Math.abs(b.qty - cur_qty)
})[0];
console.log(output, nearest)
});
当我 console.log highestArray 我得到:
[
{
"qty": 15,
"price": 18.1379,
"price_excl": 14.99
},
{
"qty": 60,
"price": 16.3229,
"price_excl": 13.49
},
{
"qty": 120,
"price": 15.1129,
"price_excl": 12.49
},
{
"qty": 240,
"price": 14.5079,
"price_excl": 11.99
}
]
为什么console.log 返回undefined 然后返回output 和nearest?
我也尝试过使用类似的函数:
changePrice(highestArray, cur_qty)
function changePrice(array,num){
var output = array.slice().reverse().find(({ qty }) => qty <= num);
if(output){
$('.price .price-new i').text(output['price'])
$('.price .vat i').text(output['price_excl'])
}
}
【问题讨论】:
-
你应该尝试过的事情:
console.log(highestArray)在你使用它之前,$.getJSON异步运行,所以$.each(..push..)在你的things I tried运行之后 -
相关:您的“我尝试过的”都返回 qty:15 条目(当highestArray 不为空时)jsfiddle.net/2n73urcm,但您声明您期望 qty:60。不太清楚 17 给出 60 的“最接近的值”是什么(那不是最低的较高值吗?)
-
@freedomn-m:你是对的。我的意思是“下一个价值”。因此,当当前值为 17 时,数组中的下一个值为 60。所以我想返回 60 的对象。当当前值为例如。 10 然后下一个值是 15。但是当我有 15 作为值时,下一个应该返回的值是 60
-
不用担心 - 这不是真正的问题,只是在查看时注意到了。您的问题是
$.getJSON的异步