๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/React

[ ๋ฆฌ์•กํŠธ(React) ] Object value์— NaN๊ฐ’์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ํ•จ์ˆ˜ ๋งŒ๋“ค๊ธฐ

by YWTechIT 2021. 6. 28.
728x90

๐Ÿ“ Object value์— NaN๊ฐ’์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ํ•จ์ˆ˜ ๋งŒ๋“ค๊ธฐ

์ฒ˜์Œ์— NaN ๊ฐ’์„ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด in, ===, !=๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ํŒ๋ณ„์ด ๋˜์ง€ ์•Š์•˜๋‹ค.


์™œ ๊ทธ๋Ÿฐ์ง€ MDN๊ณต์‹๋ฌธ์„œ์—์„œ ์ฐพ์•„๋ณด๋‹ˆ๊นŒ NaN ํŒ๋ณ„์€ ๋น„๊ต ํŒ๋ณ„ ๋Œ€์‹  isNaN() ํ˜น์€ Number.isNaN() ๋‚ด์žฅํ•จ์ˆ˜๋กœ ํŒ๋ณ„ํ•ด์•ผ ํ•œ๋‹ค๊ณ  ๋‚˜์™€์žˆ์—ˆ๋‹ค. (โญ๏ธ ๊ณต์‹๋ฌธ์„œ์˜ ์ค‘์š”์„ฑ โญ๏ธ) isNaN, Number.isNaN()์€ ๋‘˜๋‹ค NaN์„ ํŒ๋ณ„ํ•˜๋Š” ํ•จ์ˆ˜์ด์ง€๋งŒ ์ˆœ์„œ๊ฐ€ ์กฐ๊ธˆ ๋‹ค๋ฅด๋‹ค.

 

  1. isNaN(): ํ˜„์žฌ ๊ฐ’์„ ์ˆซ์ž๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  NaN ํŒ๋ณ„
  2. Number.isNaN(): ํ˜„์žฌ typeof => Number && ๊ฐ’์ด NaN ์ผ๋•Œ๋งŒ ํŒ๋ณ„

 

์ด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ key:value ํ˜•ํƒœ๋กœ ์ด๋ฃจ์–ด์ง„ ๊ฐ์ฒด์—์„œ isNaN, Number.isNaN() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋‹ˆ๊นŒ ์ •ํ™•ํ•œ ํŒ๋ณ„์ด ์ด๋ฃจ์–ด์ง€์ง€ ์•Š์•˜๋‹ค. ์™œ๋ƒํ•˜๋ฉด object ๊ฐ’์„ Number ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ํ•˜๋ฉด NaN์ด ๋‚˜์˜ค๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์ด ์ƒํƒœ์—์„œ NaN ํ•จ์ˆ˜ ํŒ๋ณ„์„ ํ•˜๊ฒŒ ๋˜๋ฉด NaN์˜ ์œ ๋ฌด์™€ ์ƒ๊ด€์—†์ด true๊ฐ€ return ๋œ๋‹ค.

 

const myObject = {name: '์•ˆ์˜์šฐ', age: 27, sex: NaN}
const yourObject = {name: '์•ˆ์˜์ค€', age: 14, sex: 'female'}

console.log(Number(myObject))
๐Ÿ‘‰๐Ÿฝ NaN

console.log(Number(yourObject))
๐Ÿ‘‰๐Ÿฝ NaN

 

๊ทธ๋ž˜์„œ isNaN, Number.isNaN() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋Œ€์‹  array๊ฐ’์—์„œ NaN์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋Š” includes() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

  1. Object์˜ Value๋งŒ์„ ๋ฝ‘์•„ array(๋ฐฐ์—ด)๋กœ ๋งŒ๋“ ๋‹ค.
  2. includes() ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•ด ๋ฐฐ์—ด์ด NaN๊ฐ’์„ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.

 

const myObject = {name: '์•ˆ์˜์šฐ', age: 27, sex: NaN}
const yourObject = {name: '์•ˆ์˜์ค€', age: 14, sex: 'female'}

const getCheckNaN = (object) => {
    let arrayValues =  Object.values(object);
    let current;

    if (arrayValues.includes(NaN)){
        current = true
    }else{
        current = false
    }
    return current
}

console.log(getCheckNaN(myInfo))
๐Ÿ‘‰๐Ÿฝ true

console.log(getCheckNaN(yourInfo))
๐Ÿ‘‰๐Ÿฝ false
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€