对象或数组的首选声明约定是什么:const还是let? [英] What is the preferred declaration convention for objects or arrays: const or let?
问题描述
我不是在问技术上可行的;我知道你可以做到
I'm not asking what's technically possible; I know you can do
const a = [];
const b = {};
a.push['sup'];
b.test = 'earth';
我想知道是否有任何约会优先选择让
over const
当涉及到将修改其内部的数组和对象时。如果您看到使用 const
声明的对象,您是否认为该对象的目的是不可变的,您是否希望看到 let
相反,或者,因为一些短信(如tslint)有问题,最好只用 const
声明它并相信其他人阅读代码知道这并不意味着它是不可变的吗?
What I'm wondering is whether there's any convention for preferring let
over const
when it comes to arrays and objects that will have their internals modified. If you see an object declared with const
, do you assume the intention was for the object to be immutable, and would you have preferred to see let
instead, or, since some linters (like tslint) have a problem with that, is it better just to declare it with const
and trust that anyone else reading the code knows that that doesn't mean it's immutable?
推荐答案
const $ c对象前面的$ c>关键字意味着有一个对象,并且您正在使用 引用 来更改它。它(正确地)意味着你不应该试图重新分配对这个对象的引用。
The const
keyword in front of an object implies that there is an object, and you're working with references to alter it. It also (correctly) implies that you should not attempt to reassign references to this object.
const obj = {a: 'foo', b: 'bar'};
const obj2 = {z: 'baz'};
obj = obj2; // const will prevent this operation.
const
并不意味着不应更改对象属性。这确实意味着您不应该尝试更改引用。
const
does not imply that the object properties should not be altered. It does imply that you should not try to change the reference.
如果您打算重新分配对象的引用,那么您使用让
。
If you plan to reassign references to the object, then you use let
.
资料来源: AirBnB Javascript风格指南
这篇关于对象或数组的首选声明约定是什么:const还是let?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!