简体   繁体   English

将扩展数组映射到数字

[英]Map spread array to numbers

When mapping an array containing integers and strings I want to cast only the numbers.映射包含整数和字符串的数组时,我只想投射数字。

Assume the array ['55', 'abc'] is passed as a param to a function.假设数组 ['55', 'abc'] 作为参数传递给函数。

How can I use the spread operator and get the same results?如何使用扩展运算符并获得相同的结果?

"Run code snippet" and notice that with the spread operator, 55 is not cast to a number. “运行代码片段”并注意使用扩展运算符,55 不会转换为数字。

 console.log(['55', 'abc'].map(val => isNaN(val) ? val : Number(val))) console.log(...[['55', 'abc']].map(val => isNaN(val) ? val : Number(val)))

How can I use the spread operator and get the same results?如何使用扩展运算符并获得相同的结果?

You can't.你不能。 Spread (which is syntax, not an operator) doesn't do mapping. Spread(这是语法,而不是运算符)不做映射。 It spreads out values.它传播价值观。 For mapping, stick with map (what you have in the first line of your code).对于映射,坚持使用map (代码的第一行中的内容)。 (Or if you were starting with something that was just array-like without actually being an array, you might use Array.from passing in a mapping callback. But your starting point in your example is an actual array.) (或者,如果您从类似数组的东西开始而不是实际数组,则可以使用Array.from传入映射回调。但您在示例中的起点是实际数组。)

The reason your second line doesn't work is that you're calling map on the outer array, which has an array in it, so val in the callback is that array.您的第二行不起作用的原因是您在外部数组上调用map ,其中包含一个数组,因此回调中的val是该数组。 isNaN(['55, 'abc']) ends up being isNaN('55,abc') which is true because '55,abc' when converted to the number type is NaN . isNaN(['55, 'abc'])最终是isNaN('55,abc')这是true因为'55,abc'转换为number类型时是NaN So the callback returns the inner array unchanged.所以回调返回内部数组不变。

Your first line creates a new array with the values mapped the way you seem to want them to be mapped.您的第一行创建了一个新数组,其中的值以您希望映射的方式进行映射。

Looks like you aren't spreading it into a new array.看起来你没有把它传播到一个新的数组中。 The below gives the desired result.下面给出了所需的结果。

 console.log(['55', 'abc'].map(val => isNaN(val) ? val : Number(val))) console.log([...['55', 'abc']].map(val => isNaN(val) ? val : Number(val)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM