本文介绍了为什么我可以在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:

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 :

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中更改常量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-20 23:40