gpt4 book ai didi

javascript - JavaScript 中的常量数组

转载 作者:行者123 更新时间:2023-12-05 08:37:24 28 4
gpt4 key购买 nike

如何在 JavaScript 中保留常量数组?

同样,在比较时,它给了我正确的结果。

例子,

const vector = [1, 2, 3, 4];

vector[2] = 7; // An element is not constant!

console.log(JSON.stringify(vector));
// [1,2,7,4] ... Was edited

// OR
const mirror = [1, 2, 7, 4];

console.log(`are equals? ${vector == mirror}`);
// false !

最佳答案

使用 Object.freeze 可以防止在对象上添加或更改值:

'use strict';
const vector = Object.freeze([1, 2, 3, 4]);

vector[2] = 7; // An element is not constant!

'use strict';
const vector = Object.freeze([1, 2, 3, 4]);
vector.push(5);

也就是说,专业 JS 中的这种代码是不寻常的,并且有点过度防御 IMO。绝对常量的常见命名约定是使用 ALL_CAPS,例如:

const VECTOR =

大型项目的另一个选择(我更喜欢)是使用 TypeScript 在编译时强制执行这些类型的规则,而无需引入额外的运行时代码。在那里,您可以:

const VECTOR: ReadonlyArray<Number> = [1, 2, 3, 4];

const VECTOR = [1, 2, 3, 4] as const;

关于javascript - JavaScript 中的常量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65658698/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com