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

javascript - Highest value of an array - Stack Overflow

programmeradmin0浏览0评论

I have an array, which contains several numbers, like this:

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")

I would like to get smallest and greatest number from this array. It seems pretty easy task, but accidently I get wrong output for code below.

function highAndLow(numbers){
var args = Array.prototype.slice.call(arguments);
var m = 0, i = 0, n = args.length;

console.log(args.length)

    for (i=0; i < n; i++) {
        if (args[i] > m) {
            m = args[i];
            console.log(m)
        }
    }

return m

}

It says length is 1 and return value is 0.

I have an array, which contains several numbers, like this:

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")

I would like to get smallest and greatest number from this array. It seems pretty easy task, but accidently I get wrong output for code below.

function highAndLow(numbers){
var args = Array.prototype.slice.call(arguments);
var m = 0, i = 0, n = args.length;

console.log(args.length)

    for (i=0; i < n; i++) {
        if (args[i] > m) {
            m = args[i];
            console.log(m)
        }
    }

return m

}

It says length is 1 and return value is 0.

Share Improve this question asked Jul 8, 2016 at 8:28 plaidshirtplaidshirt 5,70120 gold badges102 silver badges193 bronze badges 2
  • 2 That's not an array, it's a string. – deceze Commented Jul 8, 2016 at 8:30
  • make the second line var arguments = numbers.split(' '); – CompanyDroneFromSector7G Commented Jul 8, 2016 at 8:32
Add a ment  | 

7 Answers 7

Reset to default 9

You have a string as parameter. You need to split first. And convert to Number.

args = numbers.split(' ').map(Number);

A minor hint: You can use the first element as first min/max value and iterate from the second element.

function highAndLow(numbers) {
    var args = numbers.split(' ').map(Number),
        min = args[0],
        max = args[0],
        i,
        n = args.length;

    for (i = 1; i < n; i++) {
        if (args[i] < min) {
            min = args[i];
        }
        if (args[i] > max) {
            max = args[i];
        }
    }
    return { min: min, max: max };
}

console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));

You can use Math.max(), Math.min():

function highAndLow(str){
  var arr = str.split(/\s/);
  var max = Math.max.apply(Math, arr);
  var min = Math.min.apply(Math, arr);
  console.log('Max:::', max, " Min::::", min);
}

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6");

You are passing a string as parameter to your function.

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")

should be replace with

highAndLow([4, 5, 29, 54, 4, 0, -214, 542, -64, 1, -3, 6, -6]);

to actually pass an array with numbers.

function highAndLow(data) {
  var data = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6";
  var dataArr = data.split(' ').map(Number);
  var result = {};
  result.max = Math.max.apply(Math, dataArr);
  result.min = Math.min.apply(Math, dataArr);
  return result;
}
var res = highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")
console.log(res.min);
console.log(res.max);

Here is the simplest way of doing it:

function highAndLow(str) {
  str = str.split(' ').sort(function(a, b) {
    return parseInt(a) - parseInt(b)
  });
  return [str[str.length - 1],
    str[0]
  ];
}
document.write(highAndLow('4 5 29 54 4 0 -214 542 -64 1 -3 6 -6'));

The splice.call is returning some thing else not the length of array because it is seeing everything as characters.

This implementation should help out ,

  1. split the string with space using array.split(delimter) Javascript Split
  2. Then convert the splitted array to number as you do the test
  3. We loop through and test for minimum and maximum array value

// Code goes here

 
function highAndLow(numbers){
  var args = numbers.split(" ");
  
  var n= args.length;
  
  document.getElementById("argLength").innerHTML="Array Length:"+n;
  
  var i=0;
  var max = Number(args[i]);
  var min = Number(args[i]);
  
  for(i=1;i<n; i++){
    var num=Number(args[i]);
    
    if(num>max)
        max=num;
  
    if(min>num)   
      min=num;
    
  }
  
  document.getElementById("output").innerHTML=("Min:"+min+", Max:"+max);
  
}
<!DOCTYPE html>
<html>

  <head>
 
  </head>

  <body onload='highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6");'>
    
    <h1 id="argLength"></h1>
    
    <h1 id="output"> </h1>
  </body>

</html>

You can try this code.

 <script type="text/javascript">

 function highAndLow(numbers) 
 {

                var args = numbers.split(" ");                    
                console.log(args.length)
                var min = Math.min.apply(Math, args),
                max = Math.max.apply(Math, args);
                console.log(min);
                console.log(max);


 }

 highAndLow('4 5 29 54 4 0 -214 542 -64 1 -3 6 -6');
 </script>
发布评论

评论列表(0)

  1. 暂无评论