函数给出NAN而不是字符串

时间:2019-06-28 16:59:44

标签: javascript function output

我是JS的初学者,我对此功能有疑问: 首先,我定义了它:

function highAndLow(numbers){
     numbers = numbers.replace(/ /g,",");
     let high = Math.max(numbers);
     let min = Math.min(numbers);
     console.log("The max value is "+high+ ", and the minimum is "+min);
};

当我叫它时:

console.log(highAndLow("1 2 3 4 5"));

我得到以下输出:

The max value is NaN, and the minimum is NaN

所以请您先显示问题出在哪里,并谢谢您。

5 个答案:

答案 0 :(得分:1)

您犯了三个错误。

  • 您在字符串上使用replace()。它将输出一个字符串。您无法将字符串传递给Math.min/max。您应该使用split()的{​​{1}}
  • 即使您' ',数组的元素也将是字符串。您可以使用split()
  • 将其转换为数字
  • map()不希望将数组作为参数。如果要传递数组,请使用Spread Operator

Math.min/max

答案 1 :(得分:1)

尝试一下

Sub PullLocation()
    Dim i As Integer

    For i = 2 To 170
        Dim contents As String
        contents = Left(Cells(i, 35).Value, 2)
        Select Case contents
            Case "FC"
                Cells(i, 36) = "Fort Collins"
            Case "BR"
                Cells(i, 36) = "Broomfield"
            Case "BO"
                Cells(i, 36) = "Boulder"
            Case "CC"
                Cells(i, 36) = "Canon City"
            Case "FR"
                Cells(i, 36) = "Franktown"
            Case "FM"
                Cells(i, 36) = "Fort Morgan"
            Case "GU"
                Cells(i, 36) = "Gunnison"
            Case "GR"
                Cells(i, 36) = "Granby"
            Case "GJ"
                Cells(i, 36) = "Grand Junction"
            Case "GO"
                Cells(i, 36) = "Golden"
            Case "LJ"
                Cells(i, 36) = "La Junta"
            Case "LV"
                Cells(i, 36) = "La Veta"
            Case "MO"
                Cells(i, 36) = "Montrose"
            Case "SA"
                Cells(i, 36) = "Salida"
            Case "SF"
                Cells(i, 36) = "State Forest"
            Case "SS"
                Cells(i, 36) = "Steamboat Springs"
            Case Else

        End Select
    Next i
End Sub

答案 2 :(得分:1)

我认为主要的误解是:

 Math.max("1,2,3")

  Math.max(1, 2, 3)

相等(第一个是您所做的,第二个是您想要的)。在第一种情况下,您将字符串传递给Math.max,而在第二种情况下,您传递了多个数字。要将字符串转换为数字数组,可以先.split将其转换为字符串数组,然后将字符串解析为数字。然后可以将该数组作为参数传播:

  Math.max(..."1 2 3".split(" ").map(Number))

答案 3 :(得分:1)

function highAndLow(numbers) {
     numbers = numbers.split(' ').map(n => +n);
     let high = Math.max(...numbers);
     let min = Math.min(...numbers);
     return "The max value is "+ high+ ", and the minimum is "+ min;
}

console.log(highAndLow("1 2 3 4 5"));

答案 4 :(得分:1)

问题是Math.max需要一个集合,并且您正在传递一个仅包含数字的字符串。将集合转换为数组并将其传递。

function highAndLow(numbers){
     numbers = numbers.replace(/ /g,",");
     var numbersList = numbers.split(",").map(function(num){
      return parseInt(num);
     });
     let high = Math.max(...numbersList);
     let min = Math.min(...numbersList);
     console.log("The max value is "+high+ ", and the minimum is "+min);
};

console.log(highAndLow("1 2 3 4 5"));