在没有Math.max()的数字字符串中查找最大值

时间:2017-05-02 15:43:01

标签: javascript arrays string algorithm

这个功能出了什么问题,我无法弄清楚:

function highAndLow(numbers){
   var arr = numbers.split(" ");
   var largest = arr[0];
   for(var i = 1; i < arr.length; i++) {
      if(arr[i] > largest) {
         largest = arr[i];
      }
   }

   return largest;
 }

此:

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

返回6并返回542.感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

.map(Number).split()调用将字符串字符转换为数字,以便在for循环内进行正确比较。

&#13;
&#13;
function highAndLow(numbers) {
  var arr = numbers.split(" ").map(Number);
  var largest = arr[0];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] > largest) {
      largest = arr[i];
    }
  }
  return largest;
}

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

答案 1 :(得分:1)

如果您正在寻找效率较低的最少代码选项,则可以使用map和sort。

return numbers.split(" ")
              .map(Number)
              .sort(function(a, b){return a-b})
              .pop();

地图会将所有字符串更改为数字:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

数组函数排序将按升序排序:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?v=example

然后pop会从数组中获取第一个值:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop?v=example

答案 2 :(得分:0)

您在比较值时parseInt

<强>代码

function highAndLow(numbers){
   var arr = numbers.split(" ");
   var largest = arr[0];
   for(var i = 1; i < arr.length; i++) { 
      if(parseInt(arr[i]) > parseInt(largest)) {
         largest = arr[i];
      }
   }

   return largest;
 }

答案 3 :(得分:0)

一种解决方案是改变这种情况:

largest = arr[i];

到此:

largest = +arr[i];

  function highAndLow(numbers){
       var arr = numbers.split(" ");
       var largest = arr[0];
       for(var i = 1; i < arr.length; i++) {
          if(arr[i] > largest) {
             largest = +arr[i];
          }
       }

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