[๋ฌธ๋ฒ/JS] method: .every()
2023. 5. 25. 13:49ใ๐ค Language/JavaScript
.every() ???
- ๋ฐฐ์ด ์์ ๋ชจ๋ ์์๋ฅผ ํน์ ์กฐ๊ฑด์ ๋ํ์ฌ ๊ฒ์ฌํ๋ ํจ์.
- array.every(callbackFn, thisArg) ํํ๋ก ์ฌ์ฉ
- Boolean ๊ฐ์ ๋ฐํํจ
- callbackFn: Boolean ๊ฐ์ ๋ฐํํด์ผ ํจ
- thisArg: ์ ํ์ฌํญ, callbackFn์ ๋๋ด๋ ์กฐ๊ฑด
์์
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
console.log([1, , 3].every((x) => x !== undefined)); // true
console.log([2, , 2].every((x) => x === 2)); // true
// ---------------
// Modifying items
// ---------------
let arr = [1, 2, 3, 4];
arr.every((elem, index, arr) => {
arr[index + 1]--;
console.log(`[${arr}][${index}] -> ${elem}`);
return elem < 2;
});
// Loop runs for 3 iterations, but would
// have run 2 iterations without any modification
//
// 1st iteration: [1,1,3,4][0] -> 1
// 2nd iteration: [1,1,2,4][1] -> 1
// 3rd iteration: [1,1,2,3][2] -> 2
// ---------------
// Appending items
// ---------------
arr = [1, 2, 3];
arr.every((elem, index, arr) => {
arr.push("new");
console.log(`[${arr}][${index}] -> ${elem}`);
return elem < 4;
});
// Loop runs for 3 iterations, even after appending new items
//
// 1st iteration: [1, 2, 3, new][0] -> 1
// 2nd iteration: [1, 2, 3, new, new][1] -> 2
// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3
// ---------------
// Deleting items
// ---------------
arr = [1, 2, 3, 4];
arr.every((elem, index, arr) => {
arr.pop();
console.log(`[${arr}][${index}] -> ${elem}`);
return elem < 4;
});
// Loop runs for 2 iterations only, as the remaining
// items are `pop()`ed off
//
// 1st iteration: [1,2,3][0] -> 1
// 2nd iteration: [1,2][1] -> 2
์ฐธ๊ณ ๋ฌธํ
[https://devdocs.io/javascript/global_objects/array/every]
'๐ค Language > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Language/JavaScript] JS ๊ฐ๋ฐ ํ๊ฒฝ (0) | 2024.02.23 |
|---|---|
| [Language/JavaScript] JS ํน์ง(์ธํฐํ๋ฆฌํฐ ์ธ์ด) (0) | 2024.02.01 |
| [Language/JS] ์ญ์ฌ & ํน์ง (0) | 2023.10.12 |
| [JS] ์ฌ๋ฌ ํ์ผ ๊ด๋ฆฌํ๊ธฐ (0) | 2023.06.07 |
| [Language/JavaScript] ์ธ์ด์ ํน์ง (0) | 2023.04.11 |