如何使用for循环查找字符串中的最大数

它应该很简单,但是我编写的代码无论我如何调整似乎都不起作用


我尝试将字符串拆分为一个数组并使用 for 循环遍历并比较所有数字,但我一直得到错误的答案


function highAndLow(numbers){

  // ...

  numbers=numbers.split(" ");

  let lowNum=numbers[0];

  let highNum=numbers[0];


  console.log(numbers)


    for (var i = 1; i < numbers.length; i++) {

        if (numbers[i]>highNum){

            highNum=numbers[i]

        }

    else if(numbers[i]<lowNum){

    lowNum=numbers[i]

    }

}

console.log(highNum)


  return highNum+" "+lowNum

}

highNum 在应该返回 542 时一直返回 6,而 lowNum 也表现得很奇怪......


天涯尽头无女友
浏览 240回答 3
3回答

红糖糍粑

正如其他人所提到的,您的直接问题是字符串与数字不同,因此您必须将(字符串)数字转换为实际数字。除此之外,这里还有一些更短的代码。// String of space delimited numbersvar string = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6";// Split into an arrayvar nums = string.split(' ');// Use built-in Math method which with some nifty ES6 syntax// Note that Math.max/min automatically convert string args to numbervar highNum = Math.max(...nums);var lowNum = Math.min(...nums);

慕标琳琳

也许你试试这些。function highAndLow(numbers){&nbsp; numbers=numbers.split(" ");&nbsp; let lowNum =+ numbers[0];&nbsp; let highNum =+ numbers[0];&nbsp; console.log(numbers);&nbsp; for (var i = 1; i < numbers.length; i++) {&nbsp; &nbsp; &nbsp; let num =+ numbers[i];&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; if (num > highNum){&nbsp; &nbsp; &nbsp; &nbsp; highNum = num&nbsp;&nbsp; &nbsp; &nbsp; } else if(num < lowNum) {&nbsp; &nbsp; &nbsp; &nbsp; lowNum = num&nbsp; &nbsp; &nbsp; }&nbsp; }&nbsp; console.log(highNum)&nbsp; return highNum + " " + lowNum}

凤凰求蛊

您需要在使用比较之前将字符串解析为数字,否则它将按字典顺序匹配为字符串而不是数字console.log("22" > "3")console.log( "22" > 3)&nbsp; &nbsp; &nbsp; &nbsp; // implicit conversion to number&nbsp;console.log(+"22" > +"3")&nbsp; &nbsp; &nbsp;// explicitly converted to number&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript