为什么我可以在javascript中更改常量的值 [英] Why can I change value of a constant in javascript

查看:155
本文介绍了为什么我可以在javascript中更改常量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道ES6尚未标准化,但目前很多浏览器支持 const 关键字在JS。



在规范中,它写成:


常量的值不能通过重新分配更改,而
常量不能重新声明。因为这样,虽然它是
可能声明一个常量没有初始化它,这将是
无用这样做。


,当我做这样的事情:

  const xxx = 6; 
xxx = 999;
xxx ++;
const yyy = [];
yyy ='string';
yyy = [15,'a'];

我看到一切都很好 xxx 仍然 6 yyy []



但如果我做 yyy.push(6); yyy.push(1); ,我的常数数组已被更改。现在它是 [6,1] ,顺便说一句,我还是不能用 yyy = 1;



我这是一个bug,还是我错过了什么?我在最新的Chrome和FF29中尝试过它。

解决方案

文档说明:


...常量不能通过重新分配来更改

...常量不能重新声明


当您添加到数组或对象时,您不会重新分配或重新声明常量,它已被声明和分配,您只需添加到列表中即可



所以这样做很好

  const x = {}; 

x.foo ='bar';

console.log(x); // {foo:'bar'}

这个

  const y = []; 

y.push('foo');

console.log(y); // ['foo'];

但这些都不是

  const x = {}; 
x = {foo:'bar'}; //错误 - 重新分配

const y = ['foo'];
const y = ['bar']; //错误 - 重新声明

const foo ='bar';
foo ='bar2'; //错误 - 无法重新分配
var foo ='bar3'; // error - 已经声明
function foo(){}; //错误 - 已经声明


I know that ES6 is not standardized yet, but a lot of browsers currently support const keyword in JS.

In spec, it is written that:

The value of a constant cannot change through re-assignment, and a constant cannot be re-declared. Because of this, although it is possible to declare a constant without initializing it, it would be useless to do so.

and when I do something like this:

const xxx = 6;
xxx = 999;
xxx++;
const yyy = [];
yyy = 'string';
yyy = [15, 'a'];

I see that everything is ok xxx is still 6 and yyy is [].

But if I do yyy.push(6); yyy.push(1);, my constant array has been changed. Right now it is [6, 1] and by the way I still can not change it with yyy = 1;.

I this a bug, or am I missing something? I tried it in the latest chrome and FF29

解决方案

The documentation states :

...constant cannot change through re-assignment
...constant cannot be re-declared

When you're adding to an array or object you're not re-assigning or re-declaring the constant, it's already declared and assigned, you're just adding to the "list" that the constant points to.

So this works fine

const x = {};

x.foo = 'bar';

console.log(x); // {foo : 'bar'}

and this

const y = [];

y.push('foo');

console.log(y); // ['foo'];

but neither of these

const x = {};
x = {foo: 'bar'}; // error - re-assigning

const y = ['foo'];
const y = ['bar']; // error - re-declaring

const foo = 'bar'; 
foo = 'bar2';       // error - can not re-assign
var foo = 'bar3';   // error - already declared
function foo() {};  // error - already declared

这篇关于为什么我可以在javascript中更改常量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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