node.js - Constant Array in JavaScript - Stack Overflow

How can I keep an array of constants in JavaScript?And likewise, when paring, it gives me the correct

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]

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745316918a4622263.html

相关推荐

  • node.js - Constant Array in JavaScript - Stack Overflow

    How can I keep an array of constants in JavaScript?And likewise, when paring, it gives me the correct

    10小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信