本文介绍了在 JavaScript 中从数组中获取最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据属性创建以下数组,我需要能够从中获取最高和最低值,以便稍后将其传递给另一个函数.

I am creating the following array from data attributes and I need to be able to grab the highest and lowest value from it so I can pass it to another function later on.

var allProducts = $(products).children("li");
prices = []
$(allProducts).each(function () {
    var price = parseFloat($(this).data('price'));
    prices[price] = price;
});
console.log(prices[0]) <!-- this returns undefined

我的列表项看起来像这样(为了便于阅读,我进行了缩减):

My list items look like this (I have cut down for readability):

<li data-price="29.97"><a href="#">Product</a></li>
<li data-price="31.00"><a href="#">Product</a></li>
<li data-price="19.38"><a href="#">Product</a></li>
<li data-price="20.00"><a href="#">Product</a></li>

价格上的快速 console.log 向我显示了我的数组,该数组似乎已排序,因此我可以获取我假设的第一个和最后一个元素,但目前数组中的名称和值是相同的,因此每当我尝试执行价格[0],我得到未定义

A quick console.log on prices shows me my array which appears to be sorted so I could grab the first and last element I assume, but presently the names and values in the array are the same so whenever I try and do a prices[0], I get undefined

[]
19.38   19.38
20.00   20.00
29.97   29.97
31.00   31.00

感觉这是一个非常简单的问题,所以请善待:)

Got a feeling this is a stupidly easy question, so please be kind :)

推荐答案

获取数组的最小值/最大值,可以使用:

To get min/max value in array, you can use:

var _array = [1,3,2];
Math.max.apply(Math,_array); // 3
Math.min.apply(Math,_array); // 1

这篇关于在 JavaScript 中从数组中获取最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 10:15
查看更多