코딩 테스트

[프로그래머스/JS] x만큼 간격이 있는 n개의 숫자

jhlee_ 2022. 8. 16. 22:25

링크

https://school.programmers.co.kr/learn/courses/30/lessons/12954

풀이

function solution(x, n) {
    var answer = [];
    for (let i = 1; i <= n; i++) {
        answer.push(x * i)    
    }
    return answer;
}

다른 풀이

function solution(x, n) {
    return Array(n).fill(x).map((val, index) => val * (index + 1))
}

기타

Array()와 new Array()의 차이가 궁금해져서 검색해보았다.
결론적으로 배열을 생성하고 반환한다는 점에서 두개는 동일하다.
Array(...)와 같은 함수로 호출됐을때 new가 inject됨.

참고 내용1

- also create and initializes a new Array when called as a function rather than as a constructor. Thus the function call Array(...) is equivalent to the object creation expression new Array(...) with the same agruments.

- 또한 생성자가 아닌 함수로 호출 됐을 때 새로운 배열이 생성되고 초기화 됩니다. 그러므로 함수 Array(...)는 객체 생성표현 new Array(...)와 동일합니다.

https://tc39.es/ecma262/#sec-array-constructor

참고 내용2

15.4.1.1 Array ( [ item1 [ , item2 [ , … ] ] ] )
When the Array function is called the following steps are taken:
Create and return a new Array object exactly as if the standard built-in constructor Array was used in a new expression with the same arguments (15.4.2).

- Array 함수가 호출됐을 때 다음 단계를 수행한다: 
표준 내장 생성자 Array가 동일한 인수를 가지고 new 표현식을 사용한거처럼 정확하게 새로운 Array 객체를 생성하거나 반환합니다.

https://262.ecma-international.org/5.1/#sec-15.4.1

 

728x90