밤토리
728x90

오늘의 포스팅은 배열에 관한 예제입니다.

 

String을 배열로 변경하고싶거나, 배열내 연산이 필요할때 Array.from을 사용해봅니다.

사실 이 외에도 Array.from으로 할 수 있는건 생각보다 많습니다.

Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운Array 객체를 만듭니다.

 

Array.from(arrayLike[, mapFn[, thisArg]])

* arrayLike : 배열로 변환하고자 하는 객체

 

* mapFn (Optional) : map

 

* thisArg (Optional) : map 실행시 this로 사용할 값

 

  • String → 배열, 배열 내 연산 (덧셈, 곱셈 등)
// String을 배열로 변경하기
console.log(Array.from('lion'));
// @result : ['l','i','o','n']


// 배열내 연산 (1*1= 1, 2*2=4, 3*3=9)
console.log(Array.from([1, 2, 3], x => x * x));
// @result : [1, 4, 9]

console.log(Array.from([1, 2, 3], x => x + x));
// @result : [2, 4, 6]

 

  • 숫자 1부터 N개만큼 배열 채우는 방법
//숫자 1부터 N개만큼 배열 채우기
const N = 10;
console.log(Array.from({length: N}, (v, i) => i + 1));
// @result : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

 

 

Array.from() - JavaScript | MDN

Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운Array 객체를 만듭니다.

developer.mozilla.org

 

728x90
profile

밤토리

@밤토리아이티

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!