본문 바로가기
카테고리 없음

[javascript] 배열 원소들의 합

by Angry Stock 2023. 7. 13.
반응형
1. for 문 : 
    for ([initialization]; [condition]; [final-expression])
       statement
function solution(n) {
  let answer = 0;
  for (let i = 0; i < n.length; i++) {
    answer += n[i];
  }
  return answer;
}

const n = [8, 16, 27, 32, 81];

console.log('solution', solution(n));
결과

2. forEach 문
arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
function solution(n) {
  let answer = 0;
  n.forEach((element) => {
    answer += element;
  });
  return answer;
}

const n = [8, 16, 27, 32, 81];

console.log('solution', solution(n));
결과

3. reduce
arr.reduce((accumulator, currentValue, currentIndex, array) => { return ... } , initialValue);
function solution(n) {
  return n.reduce((acc, cur) => acc + cur);
}

const n = [8, 16, 27, 32, 81];

console.log('solution', solution(n));
결과

4. for of
    for (variable of iterable) {
      statement
    }
function solution(n) {
  let answer = 0;
  for (let value of n) {
    answer += value;
  }
  return answer;
}

const n = [8, 16, 27, 32, 81];

console.log('solution', solution(n));
결과

5. map
    arr.map(callback(currentValue[, index[, array]])[, thisArg])
function solution(n) {
  let answer = 0;
  n.map((a) => {
    answer += a;
  });
  return answer;
}

const n = [8, 16, 27, 32, 81];

console.log('solution', solution(n));
결과

반응형

댓글