배열은 어디에나 많이 쓰이기 때문에 한 번 정리하고 가면 좋을 거 같아 작성해본다.
every() : boolean, 모두 맞거나 틀린 것을 찾아야 할 때
some() : boolean, 하나라도 맞거나 틀린 것을 찾아야 할 때
find() : 배열에서 찾은 첫 번째 요소의 값이 필요할 때
findIndex() : 배열에서 찾은 요소의 인덱스 값이 필요할 때
includes() : boolean, 배열에 찾고 싶은 값이 있는지 알고 싶을 때
filter() : 조건을 만족하는 요소로만 새로운 배열을 만들고 싶을 때
array. every(functioin(currentValue, index, array), thisValue))
Parameter | Description |
---|---|
function | 배열의 각 값에 대해 실행할 함수 (총 3개 인자) |
currentValue | 배열 내에서 순차적으로 입력되는 엘리먼트 |
index(선택) | 현재 엘리먼트의 배열 내 index |
array(선택) | 현재 엘리먼트가 속한 배열 |
thisValue(선택) | 함수 내부에서 사용될 this에 대한 값 |
예제 1
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
예제 2
const isSubset = (array1, array2) =>
array2.every((element) => array1.includes(element));
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false
array.some(function(currentValue, index, array), thisValue))
array.find(function(element, index, array), thisArg))
array.findindex(function(currentValue, index, array), thisValue))
array.includes(searchElement, formIndex)
array.filter(function(element, index, array), thisArg)
해당하는 메소드들은 배열 전체에서 조건과 하나라도 틀린 것을 골라내거나 하나라도 맞는 것을 골라낼 때 아주 잘 쓰일 수 있을 것 같다.
참고 링크
https://paperblock.tistory.com/67
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/every