将数组与单个值乘以数字? [英] Multiplying an array with a single value by a number?

查看:122
本文介绍了将数组与单个值乘以数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么JavaScript允许您将数组与单个数值乘以另一个数值或另一个具有单个数值的数组?:

Why does JavaScript allow you to multiply arrays with a single numeric value by another numeric value or by another array with a single numeric value?:

[3] * 3;
// 9

[3] * 2;
// 6

[3] * [3];
// 9

[1, 2] * 2
// NaN

我希望每次都能返回 NaN 但是我在Chrome中的实验证明情况并非如此。

I would expect NaN to be returned every time but as my experiments in Chrome have demonstrated this is not the case.

这是预期的行为吗?这种行为有意义吗?如果是这样,为什么?

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

推荐答案

[3] * 3;

采取以下步骤:


  • 数组转换为字符串 [3] => 3

  • 字符串转换为数字数字(3)=> 3

  • 3 * 3 给出 9

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

同样,对于 [1,2] * 2


  • 数组转换为字符串 [1,2] => 1,2

  • 字符串转换为数字数字(1,2)=> NaN

  • NaN * 3 给出 NaN

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

对于ECMA我们中间的怪人;)开始此处并按照路径乘法运算符=> ToNumber => ToPrimitive => [[DefaultValue]](数字)=> valueOf => toString

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

这篇关于将数组与单个值乘以数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆