JavaScript

Javascript 문자열 배열만들기, 배열 분할/변환하기 (from, split)

ITSkeleton 2020. 6. 9. 21:44
728x90
반응형

1. from

Javascript에는 문자열을 한꺼번에 배열을 만들때나 배열을 한꺼번에 처리해야할때 편하게 해주는 from이라는 기능이 있습니다.

 

const str = '987654';

const fromStr = Array.from(str);
// fromStr: [ '9', '8', '7', '6', '5', '4' ]

const modifyStr = Array.from(fromStr, e => e*3);
// modifyStr: [ 27, 24, 21, 18, 15, 12 ]
// 뒤의 e => e*3 은 callback 함수입니다
// return 함수로 사용할 수 있습니다

 

2. split

특정한 문자를 이용하여 배열로 변환이 가능합니다

const text = 'test1,test2,test3,test4,test5';

console.log(text.split(','));
// 결과: ['test1', 'test2', 'test3', 'test4', 'test5']

const text2 = 'test1ktest2ktest3ktest4ktest5';

console.log(text.split('k'));
// 결과: ['test1', 'test2', 'test3', 'test4', 'test5']
728x90
반응형