如何在JavaScript中[1,2] + [4,5,6] [1] = 1,25 [英] How [1,2] + [4,5,6][1] = 1,25 in JavaScript

查看:67
本文介绍了如何在JavaScript中[1,2] + [4,5,6] [1] = 1,25的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从访谈中得到了这个问题,

I got this question from Interview,

[1,2] + [4,5,6][1]

JavaScript给出答案 1,25

JavaScript giving answer 1,25.

是怎么回事?请清楚地解释。

How it's happening? Please explain clearly.

推荐答案

让我们从最后一部分开始,写得更详细

Lets start with the last part and write it more verbose

var arr   = [4,5,6];
var value = arr[1];

[4,5,6][1]

和数组从零开始,得出 5 ,所以我们确实有

and as arrays are zero based, that gives 5, so we really have

[1,2] + 5;

第一部分等于

[1,2].toString(),

返回字符串 1,2 ,因为在试图将表达式用于此类表达式时,该数组会转换为字符串,因为不能将数组添加到数字中,然后我们有

and that returns the string "1,2" because the array is converted to a string when trying to use it in an expression like that, as arrays can't be added to numbers, and then we have

"1,2" + 5

将字符串与数字连接会得到字符串,并将字符串加在一起得到

Concatenating strings with numbers gives strings, and adding the strings together we get

"1,25"

这篇关于如何在JavaScript中[1,2] + [4,5,6] [1] = 1,25的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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