Maison > Questions et réponses > le corps du texte
Dans le code ci-dessous, j'ai défini quelques constantes. Je veux utiliser Symbol
pour m'assurer que chaque constante est unique. Mais quand j'utilise la ligne de code suivante :
if (isBtnDigitizePolygonClicked.value == true) { return polygDigiConstants.CONST_STRING_DIGITIZE; }
La valeur renvoyée par le code ci-dessus est Symbol('Digitize')
,但我期望它是Digitize
, comme décrit dans ce tutoriel : https://www.scaler.com/topics/enum-in-javascript/
Contenu du didacticiel :
const Direction = Object.freeze({ North: Symbol('north'), East: Symbol('east'), West: Symbol('west'), South: Symbol('south'), }) const Pole = Object.freeze({ North: Symbol('north'), South: Symbol('south'), }) console.log(Direction.North === Pole.North) 上述代码的输出为: false
Veuillez me dire comment utiliser Symbol
correctement pour définir les propriétés.
polygDigiConstants.js
function define(name, value) { Object.defineProperty(polygDigiConstants, name, { value: value, enumerable: true, writable: false, }); } export let polygDigiConstants = {}; define('CONST_STRING_DIGITIZE', Symbol('Digitize')); define('CONST_STRING_STOP_DIGITIZE', Symbol('Stop')); define('CONST_STRING_CLEAR_DIGITIZED', Symbol('Clear'));
P粉2001385102023-09-19 11:37:35
polygDigiConstants.js
function define(name, value) { Object.defineProperty(polygDigiConstants, name, { value: value, enumerable: true, writable: false, }); } export let polygDigiConstants = {}; define('CONST_STRING_DIGITIZE', Symbol('Digitize')); define('CONST_STRING_STOP_DIGITIZE', Symbol('Stop')); define('CONST_STRING_CLEAR_DIGITIZED', Symbol('Clear'));
JS
import { polygDigiConstants } from './polygDigiConstants.js'; if (isBtnDigitizePolygonClicked.value == true) { return polygDigiConstants.CONST_STRING_DIGITIZE.description; // 这将给你 'Digitize' } function define(name, value) { Object.defineProperty(polygDigiConstants, name, { value: value, enumerable: true, writable: false, }); } export let polygDigiConstants = {}; define('CONST_STRING_DIGITIZE', 'Digitize'); define('CONST_STRING_STOP_DIGITIZE', 'Stop'); define('CONST_STRING_CLEAR_DIGITIZED', 'Clear');
polygDigiConstants.CONST_STRING_DIGITIZE vous donnera directement la chaîne 'Digitize'.