.includes() / .indexOf()
30 Jan 2023 -
Less than 1 minute read
π μλ°μ€ν¬λ¦½νΈ 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('π');
}
// π
// π