본문 바로가기
JavaScript/메소드

[javascript] Array.from(), Array(), fill()

by Angry Stock 2023. 8. 15.
반응형
1. Array.from(arrayLike[, mapFn[, thisArg]])
2.
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)
3. arr.fill(value[, start[, end]])
function solution1(n) {
  let answer = [[]];
  for (let i = 0; i < n; i++) {
    answer[i] = Array(n).fill(0, 0, n);
    answer[i][i] = 1;
  }
  return answer;
}

function solution2(n) {
  const answer = Array.from(Array(n), (a) => (a = Array(n).fill(0)));
  for (let i = 0; i < n; i++) {
    answer[i][i] = 1;
  }
  return answer;
}

function solution3(n) {
  const answer = Array.from(Array(n), () => Array(n).fill(0));
  for (let i = 0; i < n; i++) {
    answer[i][i] = 1;
  }
  return answer;
}

console.log('solution1', solution1(4));
console.log('solution2', solution2(5));
console.log('solution3', solution3(3));
결과

반응형

댓글