字符串的扩展运算符

Spread operator for strings

我在 MDN 上阅读了有关 扩展语法 的内容,它可以与数组和字符串一起使用:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) are expected - mdn.

我对数组很清楚。它会将元素扩展为单独的参数。
但是我没有找到字符串的例子。

那么,在函数调用中使用扩展语法扩展字符串的规则是什么?
字符串字符是否应该用空格分隔因为我试过这个并且它打印了 3.

var x = "1 2 3";
console.log(Math.max(...x));

正如我们在下面看到的,您的示例实际上传播到 5 个元素,其中 2 个是 space 个字符。您还可以在下面看到,字符串上的扩展运算符似乎与使用 .split('').

相同

const x = "1 2 3";
console.log([...x]);

console.log(x.split(''));

var x = "123";
console.log(Math.max(...x));

// prints 3

... 将字符串视为可迭代对象,相当于一个字符映射到一个元素的数组。

Math.max 对空字符串的计算类似于 +" "Number(" ") 因此 0

let num = "1 2 3";

console.log( Math.max(...num))  // ["1"," ","2"," ","3"] >>> [1,0,2,0,3] >>> 3

因此直接用数字扩展字符串是不明智的,因为 34 8 9 将最大为 9
总是事先用你的分隔符 num.split(" ") 分开。

扩展语法将产生 5 个元素,其中 2 个是 space 个字符:

const x = "1 2 3";
console.log([...x]);

//=> ["1", "", "2", "", "3"]


详细:

扩展运算符的结果将是 ["1", "", "2", "", "3"],其中包含 space 个字符。

根据这个结果,Math.max() 将通过将非数字类型转换为数字来尝试找到数组中最大的数字,类似于 运行 Number("1")String 转换为 Number。 space 字符被转换为数字 0,类似于 Number("") === 0.

因此,您将得到以下数字列表:[ 1, 0, 2, 0, 3 ] Math.max() 将选择 3 作为最大数字全部.