[๋ฌธ๋ฒ•/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]