理解Javascript不可变变量 [英] Understanding Javascript immutable variable
问题描述
我试图理解Javascript不可变变量的含义。如果我能做到:
I am trying to understand what a Javascript immutable variable means. If I can do:
var x = "astring";
x = "str";
console.log(x); //logs str` , then why it is immutable?
我能想到的唯一答案(从CI的一点点知道)是var x是一个指向具有值astring的内存块的指针,在第二个语句之后,它指向另一个值为str的块。是这样吗?
The only answer I can think (from the little bit of C I know) is that var x is a pointer to a memory block with the value "astring", and after the 2nd statement it points to another block with the value "str". Is that the case?
还有一个奖励问题:我对Javascript的值类型感到困惑。引擎盖下的所有变量都是对象吗?偶数和字符串?
And a bonus question: I was confused by the value types of Javascript. Are all variables objects under the hood? Even number and strings?
推荐答案
值是不可变的; 变量不是;它们包含对它们(原始)值的引用。
Values are immutable; variables are not; they hold a reference to their (primitive) values.
三种基本类型 string,number和boolean 具有对应的类型,其实例是对象: String,Number,Boolean 。
它们有时被称为 包装类型 。
The three primitive types string, number and boolean have corresponding types whose instances are objects: String, Number, Boolean.
They are sometimes called wrapper types.
以下值为原始的:
- 字符串:你好
- 数字:6,3.14( JavaScript中的所有数字都是浮点数)
- 布尔值:true,false
- null:通常明确分配
- undefined:通常是默认值(自动赋值)
- Strings: "hello"
- Numbers: 6, 3.14 (all numbers in JavaScript are floating point)
- Booleans: true, false
- null: usually explicitly assigned
- undefined: usually the default (automatically assigned) value
所有其他值都是对象,包括基元的包装器。
All other values are objects, including wrappers for primitives.
所以:
- 默认情况下对象是可变的
- 对象具有唯一标识并通过引用进行比较
- 变量保持对对象的引用
- 基元是不可变的
- 基元按价值进行比较,它们没有个人身份
- Objects are mutable by default
- Objects have unique identities and are compared by reference
- Variables hold references to objects
- Primitives are immutable
- Primitives are compared by value, they don’t have individual identities
你可能会发现 JavaScript Primitives的秘密生活一个很好的解释。
You might find The Secret Life of JavaScript Primitives a good explanation.
此外,在ES6中有一个新的 const 关键字,它创建一个只读的命名常量,它不能通过赋值来改变值,或者在脚本运行时重新声明。
Also, in ES6 there is a new const keyword, that creates a read-only named constant that cannot change value through assignment or be re-declared while the script is running.
希望这有帮助!
这篇关于理解Javascript不可变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!