最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Constant Array in JavaScript - Stack Overflow

programmeradmin1浏览0评论

How can I keep an array of constants in JavaScript?

And likewise, when paring, it gives me the correct result.

Example,

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 !

How can I keep an array of constants in JavaScript?

And likewise, when paring, it gives me the correct result.

Example,

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 !
Share Improve this question asked Jan 10, 2021 at 21:30 Alexandra Danith AnsleyAlexandra Danith Ansley 3382 silver badges15 bronze badges 1
  • Thanks for the answers. I tried clicking "This answare is useful", but stackoverflow won't let me do it yet. I'm new around here. – Alexandra Danith Ansley Commented Jan 11, 2021 at 17:03
Add a ment  | 

3 Answers 3

Reset to default 8

With Object.freeze you can prevent values from being added or changed on the object:

'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);

That said, this sort of code in professional JS is unusual and a bit overly defensive IMO. A mon naming convention for absolute constants is to use ALL_CAPS, eg:

const VECTOR =

Another option for larger projects (that I prefer) is to use TypeScript to enforce these sorts of rules at pile-time without introducing extra runtime code. There, you can do:

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

or

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

I have not investigated thoroughly, but it is inferred that JS will have immutable native types, here is a presentation:

https://2ality./2020/05/records-tuples-first-look.html

const vector = #[1, 2, 3, 4]; // immutable

The const keyword can be confusing, since it allows for mutability. What you would need is immutability. You can do this with a library like Immutable or Mori, or with Object.freeze:

const array = [1,2,3]
Object.freeze(array)
array[0] = 4
array // [1,2,3]
发布评论

评论列表(0)

  1. 暂无评论