我最近在JavaScript中遇到了const关键字。据我所知,它是用来创建不可变变量的,我已经测试了,以确保它不能被重新定义(在Node.js中):

const x = 'const';
const x = 'not-const';

// Will give an error: 'constant 'x' has already been defined'

我意识到它还没有在所有浏览器上标准化——但我只对Node.js V8的环境感兴趣,我注意到某些开发人员/项目似乎非常喜欢它,当var关键字可以用于同样的效果时。

什么时候用const代替var比较合适? 它是否应该被用在每一个不存在的变量上 重新分配是声明的? 如果用var来代替,会有什么不同吗 Const还是反之?


当前回答

Const不是不可变的。

来自MDN:

const声明创建一个对某个值的只读引用。它 这并不意味着它持有的值是不可变的,只是变量 标识符不能重新分配。

其他回答

var:声明一个变量。值初始化是可选的。

let:声明一个块范围的局部变量。

const:声明一个只读命名常量。

例子:

var a;
a = 1;
a = 2; // Reinitialize possible
var a = 3; // Re-declare
console.log(a); // 3

let b;
b = 5;
b = 6; // Reinitialise possible
// let b = 7; // Redeclare not possible
console.log(b);

// const c;
// c = 9;    // Initialization and declaration at the same place
const c = 9;
// const c = 9; // Redeclare and initialization is not possible
console.log(c); // 9
// NOTE: Constants can be declared with uppercase or lowercase, but a common
// convention is to use all-uppercase letters.

对于为什么使用const, Tibos的回答很好。

但是你说:

据我所知,它是用来创建不可变变量的

这是错误的。改变变量不同于重新赋值:

var hello = 'world' // Assigning
hello = 'bonjour!' // Reassigning

使用const,你不能这样做:

const hello = 'world'
hello = 'bonjour!' // Error

但是你可以改变你的变量:

const marks = [92, 83]
marks.push(95)
console.log(marks) // [92, 83, 95] -> the variable has been mutated.

因此,任何不使用=号而改变变量值的进程都是在改变变量。

注:+=例如…重新分配!

var a = 5
a += 2 // Is the same as a = a + 2

所以,底线是:const不会阻止你改变变量;它阻止您重新分配它们。

我的意见:

问:什么时候用const代替var比较合适? 答:从来没有!

Q:每次声明一个不会被重新赋值的变量时都应该使用它吗? 答:从来没有!就像这将减少资源消耗一样……

问:用var代替const和用var代替const有什么区别吗? 答:是的!使用var是正确的方法!更容易在开发工具和节省创建一个新的文件进行测试。(var不在const的位置- const试图取代var的位置…)

额外A: let也是一样。JavaScript是一种松散的语言——为什么要限制它?

当涉及到let和const(都是块作用域)之间的决定时,总是首选const,以便在代码中使用清楚。这样,如果您试图重新声明变量,就会得到一个错误。如果没有其他选择,只能重新声明它,只需转换为let。注意,正如Anthony所说,const值不是不可变的(例如,const对象的属性可以发生变化)。

When it comes to var, since ES6 is out, I never used it in production code and can't think of a use case for it. One point that might consider one to use it is JavaScript hoisting - while let and const are not hoisted, var declaration is. Yet, beware that variables declared with var have a function scope, not a block scope («if declared outside any function, they will be globally available throughout the program; if declared within a function, they are only available within the function itself», in HackerRank - Variable Declaration Keywords). You can think of let as the block scoped version of var.

Const不是不可变的。

来自MDN:

const声明创建一个对某个值的只读引用。它 这并不意味着它持有的值是不可变的,只是变量 标识符不能重新分配。