简体   繁体   中英

Object.values seems not to work in enum type

I have this enum defined in my app:

export enum Status {
    BOOKED = 'B',
    FREE = 'F',
}

and I add this message on the console

console.log ('<------------------------------------>');
        console.log (code.value);
        console.log (Object.values(Status));
        console.log (code.value in Object.values(Status));
        console.log ('<------------------------------------>');

 <------------------------------------>

and I see this on the console, code.value is not included in the enum; I should see true

    B
    [ 'B', 'F' ]
   false

You have this object

export enum Status {
    BOOKED = 'B',
    FREE = 'F',
}

Object.values(Status) will give you [ 'B', 'F' ] which is expected

Read this for more info -

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

You should use array.include() to check if an array contain a value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

const values = Object.values(Status);
console.log(values.includes(code.value));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM