为什么`new Array(4).join(""+10) + "蝙蝠侠!"`返回“NaNNaNNaN蝙蝠侠!" [英] Why does `new Array(4).join(""+10) + " Batman!"` return "NaNNaNNaNNaN Batman!"

查看:20
本文介绍了为什么`new Array(4).join(""+10) + "蝙蝠侠!"`返回“NaNNaNNaN蝙蝠侠!"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个在线视频中看到了这个片段(如果有人能找到链接,请随时将其添加到问题中).

视频很短,所以没有解释为什么 JavaScript 返回这个真正随机的字符串.

这可能与 JavaScript 处理某些类型的方式有关...

解决方案

它没有:

console.log(new Array(4).join(""+10) + " Batman!")预>

然而,这样做:

console.log(new Array(5).join("a"-10) + " Batman!")

您的代码无法运行,原因有两个:

  1. 一个字符串和一个数字的加法被解释为字符串连接,所以 ""+10 变成了字符串 "10".你必须使用减法.
  2. 即便如此,更改为减法还是不够的,因为空字符串 "" 转换为数字 0 并导致 0-10> 这是数字 -10 最终通过 join() 转换为字符串 "-10" .您必须在引号中添加一些无效数字.

这样做的原因是 JavaScript 看到减法并尝试将字符串 "a" 转换为数字,但它不是有效数字,因此返回 NaN(意思是不是数字").然后它尝试从中减去 10,这也返回 NaN.结果是您调用了 new Array(5).join('NaN'),它将 5 个空数组元素与字符串 "NaN" => NaNNaNNaNNaN 连接起来然后将字符串 " Batman!" 连接到它.

I saw this snippet in a video online (if anyone can find the link, please feel free to add it to the question).

The video was quite short, so there was no explanation as to why JavaScript returns this really random string.

This probably has something to do with how JavaScript handles certain types...

解决方案

It doesn't:

console.log(new Array(4).join(""+10) + " Batman!")

However, this does:

console.log(new Array(5).join("a"-10) + " Batman!")

Your code didn't work because of two reasons:

  1. Addition with a string and a number gets interpreted as string concatenation, so ""+10 becomes the string "10". You have to use subtraction.
  2. Even so, changing to subtraction isn't enough because the empty string "" converts to the number 0 and results in 0-10 which is the number -10 which finally gets converted to the string "-10" by join(). You have to put something into the quotes that is not a valid number.

The reason it behaves this way, is that JavaScript sees the subtraction and tries to convert the string "a" into a number, but it's not a valid number so it returns NaN (meaning "not a number"). It then tries to subtract 10 from it, which also returns NaN. The result is that you're calling new Array(5).join('NaN'), which joins 5 empty array elements with the string "NaN" => NaNNaNNaNNaN and then concatenating the string " Batman!" to it.

这篇关于为什么`new Array(4).join(""+10) + "蝙蝠侠!"`返回“NaNNaNNaN蝙蝠侠!"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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