JavaScript中的数字是不可变的吗? [英] Is number in JavaScript immutable?

查看:89
本文介绍了JavaScript中的数字是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

javascript numbers- immutable

我读过Douglas Crockford的书:JavaScript:好零件。它说JavaScript中的数字是不可变的。但JavaScript中的数字是按值复制的,我们可以使用operator ++来更改值。那么为什么说这是不可改变的呢?而且,如果它是
不可变,为什么数字会按值复制?

I read Douglas Crockford's book JavaScript: the Good Parts. It says the number in JavaScript is immutable. But numbers in JavaScript is copied by value and we can use operator ++ to change the value. So why say it's immutable? and further, if it's immutable, why numbers are copied by value?

推荐答案

它们是不可变的,因为它们是按值复制的。

They are immutable because they are copied by value.

当你这样做时

var x = 4;
x += 1;

您没有更改数字 4 到数字 5 。您已将变量 x 中存储的值从 4 更改为 5

you haven't changed the number 4 into the number 5. You have changed the value stored in the variable x from 4 to 5.

这篇关于JavaScript中的数字是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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