最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - Compare Integer against an Array of Integers - Stack Overflow

programmeradmin0浏览0评论

Is there a way to pare an integer against an array of integers? For instance, to determine if an int is larger than any of the array ints?

var array = [1, 2, 3, 4];
if(5 > array){ 
    // do something 
}

Update: I guess I meant, is 5 larger than the largest number in the array. Thanks!

Is there a way to pare an integer against an array of integers? For instance, to determine if an int is larger than any of the array ints?

var array = [1, 2, 3, 4];
if(5 > array){ 
    // do something 
}

Update: I guess I meant, is 5 larger than the largest number in the array. Thanks!

Share Improve this question edited Jun 6, 2012 at 23:42 matthoiland asked Jun 6, 2012 at 23:33 matthoilandmatthoiland 91211 silver badges24 bronze badges 2
  • 1 Judging from your choice of example, I assume you mean "larger than all of the array ints"? Or did you really mean "any"? – Mark Byers Commented Jun 6, 2012 at 23:36
  • @MarkByers. Yeah I think you're right... – gdoron Commented Jun 6, 2012 at 23:40
Add a ment  | 

3 Answers 3

Reset to default 8

You can use Math.max and apply

if (5 > Math.max.apply(Math, array)) {
    // do something
}

Update: To explain as it works. It's described in the docs I linked but I will try to be more clear here:

Math.max returns the largest of zero or more numbers, so:

Math.max(1, 2, 3, 4) // returns 4

apply calls a function with a given 'this' value (the first argument) and arguments provided as an array (the second). so:

function sum(a, b) {
    return a + b;
}

console.log(sum.apply(window, [2, 3])); // 5

Therefore, if you have an array of integers and you want to get the max, you can bine them to have:

console.log(Math.max.apply(Math, [1, 2, 3, 4])); // 4

Because it's exactly like have:

console.log(Math.max(1, 2, 3, 4));

The difference is you pass an array instead.

Hope it's more clear now!

There is no good and readable built in way of doing it, but it can be done simply with:

var bigger = true;
for (var i =0; i < array.length; i++) {
    if (5 <= array[i]) {
        bigger = false;
        // you can add here : break;
    }
}

Sure, you could sort the array, take the last element, and see if your integer is greater than that. Or, you could loop through and check each one. Up to you. The loop is a more performant way.

//maybe check the bounds on this if you know it can be a blank array ever
var max = myArray[0];
for(var x = 0; x < myArray.length; x++) {
    max = Math.max(max, myArray[x]);
}

if(500 > max) {
    //do something
}
发布评论

评论列表(0)

  1. 暂无评论