.includes() / .indexOf()


πŸ“‘ μžλ°”μŠ€ν¬λ¦½νŠΈ Array / Array Method


.includes()



  • λ¬Έμžμ—΄μ΄ νŠΉμ • λ¬Έμžμ—΄μ„ ν¬ν•¨ν•˜λŠ”μ§€ ν™•μΈν•˜λŠ” λ©”μ„œλ“œ

  • μ‘΄μž¬ν•˜λ©΄ true, μ‘΄μž¬ν•˜μ§€ μ•ŠμœΌλ©΄ false 리턴

    • includes(searchElement)

    • includes(searchElement, n) : n번째 μΈλ±μŠ€λΆ€ν„° 검색

ex)

var array = [1, 30, 23, 11];
console.log(array.includes(23));    //true
console.log(array.includes(2));     //false

var strArray = ['red', 'blue', 'green', 'black'];
console.log(strArray.includes('blue', 1));  //true
console.log(strArray.includes('blue', 2));  //false



.indexOf()



TypeError : κ°œμ²΄κ°€ β€˜includes’ μ†μ„±μ΄λ‚˜ λ©”μ„œλ“œλ₯Ό μ§€μ›ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.


크둬에선 잘 되던 includes(),, 엣지/μΈν„°λ„·μ΅μŠ€ν”Œλ‘œλŸ¬μ—μ„œ TypeErrorκ°€ λ°œμƒν–ˆλ‹€ 😣
➑ λͺ¨λ“  λΈŒλΌμš°μ €μ—μ„œ μ§€μ›ν•˜λŠ” indexOf()둜 λ°”κΏ”μ£Όμž πŸ™ƒ


  • λ¬Έμžμ—΄μ—μ„œ ν•΄λ‹Ή λ¬Έμžκ°€ ν¬ν•¨λœ 인덱슀 리턴

  • μ‘΄μž¬ν•˜μ§€ μ•ŠμœΌλ©΄ -1 리턴

    • indexOf(searchElement)

    • indexOf(searchElement, n) : n번째 μΈλ±μŠ€λΆ€ν„° 검색

ex)

var array = [1, 30, 23, 11];
console.log(array.indexOf(23));     //2
console.log(array.indexOf(2));      //-1

var strArray = ['red', 'blue', 'green', 'black'];
console.log(strArray.indexOf('blue', 1));   //1
console.log(strArray.indexOf('blue', 2));   //-1
console.log(strArray.indexOf('blue', -1));  //-1



.includes & .indexOf()



var array = ['hi', 'bonjour', 'hola'];

if (array.includes('hi')) {
    console.log('πŸ‘‹');
}

if (array.indexOf('hi') != -1) {
    console.log('πŸ™Œ');
}

// πŸ‘‹
// πŸ™Œ

Categories:

Javascript