Home > OS >  what is the difference between .split(" ") and ...array
what is the difference between .split(" ") and ...array

Time:08-31

I am trying to get the max and min numbers from str = "8 3 -5 42 -1 0 0 -9 4 7 4 -4"

The first method gives the correct answer using .min(...arr) but the second method using .min(arr) returns NAN. I thought the spread operator and the split method both created an array that could be passed into Math. What is the difference between the two.

function highAndLow(str){
    let arr = str.split(" ")
    let min = Math.min(...arr)
    let max = Math.max(...arr)
    return max   " "   min
  }

function highAndLow2(str){
    let arr = str.split(" ")
    let min = Math.min(arr)
    let max = Math.max(arr)
    return max   " "   min 
  }

CodePudding user response:

The Math.min/max functions accept a number as an argument. You can see in the documentation that:

The static function Math.min() returns the lowest-valued number passed into it, or NaN if any parameter isn't a number and can't be converted into one.

That is why, when you don't use the spread operator, you are passing in the array and you are getting NaN as a return value.

The Split operator:

takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

It does something completely different than the Spread operator and is used for other purposes.

I would advise you read more about the Spread operator here.

CodePudding user response:

Math.min does not accept an array,

you need to destructure your array like so :

function highAndLow2(str){
    let arr = str.split(" ")
    let min = Math.min(...arr)
    let max = Math.max(...arr)
    return max   " "   min 
}

which gives a result of '42 -9'

CodePudding user response:

Math.min() or Math.max() does not accept an array, it is accepted as arguments. The spread operator (...arr) actually expands collected elements such as arrays into separate elements. split(" ") actually converts a string to array. If you want to get min or max value from an array then you have to use apply() like Math.min.apply(null, arr) or Math.max.apply(null, arr)

  • Related