在JavaScript数组获取最大值和最小值 [英] Get max and min value from array in JavaScript

查看:181
本文介绍了在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显示我我的数组这似乎进行排序,所以我可以抢我想第一个和最后一个元素,但是presently数组中的名称和值是一样的,所以每当我尝试并做了价格[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数组获取最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆