javascript enum
In JavaScript, there is no built-in support for enums like in some other programming languages. However, you can create an enum-like behavior using objects or constants.
Here is an example of creating an enum-like behavior using objects:
const Colors = {
RED: 'red',
GREEN: 'green',
BLUE: 'blue'
};
console.log(Colors.RED); // Output: red
console.log(Colors.GREEN); // Output: green
console.log(Colors.BLUE); // Output: blue
In this example, Colors is an object that acts as an enum. Each property of the object represents a value of the enum. You can access the values using dot notation.
Alternatively, you can create an enum-like behavior using constants:
const RED = 'red';
const GREEN = 'green';
const BLUE = 'blue';
console.log(RED); // Output: red
console.log(GREEN); // Output: green
console.log(BLUE); // Output: blue
In this example, each constant represents a value of the enum. You can access the values directly using the constant names.
Note that these approaches do not enforce the immutability of the enum values like in some other languages. It is still possible to modify the values of the objects or constants
原文地址: https://www.cveoy.top/t/topic/iMKg 著作权归作者所有。请勿转载和采集!