Multiplying an array with one value by a number?

Why does JavaScript allow you to multiply arrays with one numerical value by another numerical value or by another array with one numerical value ?:

[3] * 3; // 9 [3] * 2; // 6 [3] * [3]; // 9 [1, 2] * 2 // NaN 

I would expect NaN to return every time, but as my experiments in Chrome showed, this is not the case.

Is this the expected behavior? Does this make sense? If so, why?

+6
source share
3 answers
 [3] * 3; 

The following steps are taken:

  • array is converted to string [3] => "3"
  • string is converted to Number Number("3") => 3
  • 3 * 3 gives 9

Similarly, for [1, 2] * 2 :

  • the array is converted to the string [1, 2] => ""1,2"
  • string is converted to Number Number("1,2") => NaN
  • NaN * 3 gives NaN

For ECMA lovers among us;) run here and follow the path multiplicative operator => ToNumber => ToPrimitive => [[DefaultValue]](number) => valueOf => toString

+9
source

What happens here is that [3] forced to a String type, which is just "3" . Then, in "3" * 3 value of String "3" converted to 3 . Finally, you get 3 * 3 , which is rated as 9 .

This behavior can be seen if you execute [3].toString() * 3 or "3" * 3 , which also gives you 9 .

So, the following steps are performed:

  • [3] * 3
  • [3].toString() * 3
  • "3" * 3
  • Number("3") * 3
  • 3 * 3
  • 9

In the case of [1, 2] you end up with "1, 2" . But Number("1, 2") leads to a NaN , and a number times a NaN leads to NaN .

+3
source

http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.2

Since Array.prototype.valueOf is not available, it reverts to using the String version (according to http://ecma-international.org/ecma-262/5.1/#sec-9.9 )

ToString displays an array with a single element as the value of the element (so [3] .toString () is 3)

+1
source

Source: https://habr.com/ru/post/948080/


All Articles