Post
.includes로 배열의 중복값 확인
(1) 문자 배열
JavaScript
const animals = ["lion", "dog", "cat", "fox"];
console.log(animals.includes("dog")); // true
console.log(animals.includes("monkey")); // false
배열.includes는 중복되는 값이 있을 시 true, 없을 때는 false를 반환한다.
(2) 숫자 배열
const numbers = [55, 22, 14, 67];
console.log(numbers.includes(14)); // true
console.log(numbers.includes("14")); // false
console.log(numbers.includes(Number("14"))); // true
숫자로 이루어진 배열일 때도 정상적으로 기능한다.
(3) 오브젝트 배열
const animals = [
{ name: "lion", size: "big" },
{ name: "dog", size: "middle" },
{ name: "cat", size: "small" },
{ name: "fox", size: "small" },
];
console.log(animals.includes("dog")); // false
console.log(animals.includes("monkey")); // false
console.log(animals.includes({ name: "dog", size: "middle" })); // false
그러나 오브젝트 배열일 때는 잘 기능하지 않는다.
'JavaScript related' 카테고리의 다른 글
| JavaScript innerHTML (0) | 2023.01.27 |
|---|---|
| JavaScript Nullish Coalescing Operator (0) | 2023.01.27 |
| JavaScript How to add JSON to localStorage (0) | 2023.01.26 |
| JavaScript addEventListener("keyup") (1) | 2023.01.26 |
| JavaScript forEach (0) | 2023.01.26 |