我最近在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,就像你说的,它不会被重新赋值并且是常量。例如,如果你想分配你的生日。你的生日永远不变,所以你可以把它作为一个常数。但你的年龄确实在变化,所以这可能是一个变量。

其他回答

简介:

Const创建一个不可变绑定,这意味着Const变量标识符是不可重赋的。

const a = "value1";

你不能用

a = "value2";

然而,如果const标识符包含一个对象或数组,只要不重新赋值,它的值就可以更改。

const x = { a: 1 }

x.a = 2; // Is possible and allowed

const numbers = [1, 2];
numbers.push(3); // Is possible and allowed

请注意,const是块作用域,就像let一样,它与var不同(var是函数作用域)。

简而言之,当某些东西不太可能通过重赋来改变时,使用const,否则使用let或var,这取决于你想要的作用域。

当可以通过重赋改变什么,不能通过重赋改变什么的时候,对代码进行推理就容易得多了。将const对象更改为let对象非常简单。在默认情况下使用const会让您三思而后行。在很多情况下,这是一件好事。

你的问题有两个方面:使用const而不是var的技术方面是什么,以及这样做与人有关的方面是什么。

技术上的差异是显著的。在编译语言中,常量将在编译时被替换,它的使用将允许其他优化,如删除死代码,以进一步提高代码的运行时效率。最近(使用较少的术语)JavaScript引擎实际上编译JS代码以获得更好的性能,因此使用const关键字将通知它们上述优化是可能的并且应该完成。这将导致更好的性能。

The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.

你回答得很好,但还是简单点吧。

当你有一个定义的常量时,应该使用Const(理解为:它在程序执行期间不会改变)。

例如:

const pi = 3.1415926535

如果你认为这是在以后的执行中可能会改变的东西,那么就使用var。

根据这个例子,实际的区别是,使用const时,你总是假设pi将是3.14[…],这是事实。

如果你把它定义为一个变量,它可能是3.14[…]或者不是。

从更专业的角度来说,Tibos的理论在学术上是正确的。

它提供了:

常量引用,例如,const x =[]——数组可以被修改,但x不能指向另一个数组;而且 块范围。

在ECMAScript 6/2015中,const和let将一起替换var。参见JavaScript ES6变量声明let和const中的讨论

对于为什么使用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不会阻止你改变变量;它阻止您重新分配它们。