String의 유용한 메서드들
let str = "hello world ! ^^ ~~";
let matchstr = "hello";
console.log(str.startsWith(matchstr));
console.log(str.endsWith(matchstr));
console.log("include test", str.includes("world"));
>>
true
false
"include test"
true
for of - 순회하기
var data = [1,2,undefined,NaN,null,""];
Array.prototype.getIndex = function(){};
data.forEach(function(value){
console.log("valueis", value)
});
>>
"valueis"
1
"valueis"
2
"valueis"
undefined
"valueis"
NaN
"valueis"
null
"valueis"
""
for(let idx in data){
console.log(data[idx]);
}
// array에서 for in을 쓰면 안되는 이유: object의 구성까지 전부 출력
>>
1
2
undefined
NaN
null
""
function(){}
for(let value of data){
console.log(value);
}
>>
1
2
undefined
NaN
null
""
var str = "hello world!!!";
for(let value of str){
console.log(value);
}
>>
"h"
"e"
"l"
"l"
"o"
" "
"w"
"o"
"r"
"l"
"d"
"!"
"!"
"!"
spread operator - 배열의 복사
: 펼침 연산자, immutable array 즉 배열을 바꾸지 않고 새로운 값을 복사하는 방법을 제공, 배열의 각 요소를 함수의 parameter로 전달할 때 유용
let pre = [100,200,"hello",null];
let newData = [0,1,2,3, ...pre, 4];
console.log(newData);
>> [0, 1, 2, 3, 100, 200, "hello", null, 4]
function sum(a,b,c){
return a+b+c;
}
let pre = [100,200,300];
// 예전
console.log(sum.apply(null, pre));
>> 600
// spread operator 이용
console.log(sum(...pre));
>> 600
from 메서드로 진짜 배열 만들기
// arguments로 가변값 입력을 대처
function addMark(){
let newData = [];
for(let i=0; i<arguments.length; i++){
newData.push(arguments[i]+"!");
}
console.log(newData);
}
addMark(1,2,3,4,5);
>> ["1!", "2!", "3!", "4!", "5!"]
function addMark(){
let newData = arguments.map(function(value){
return value + "!";
})
console.log(newData);
}
addMark(1,2,3,4,5);
>>
"error"
"TypeError: arguments.map is not a function
at addMark (foruvebiti.js:3:27)
at foruvebiti.js:10:1
at https://static.jsbin.com/js/prod/runner-4.1.8.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.8.min.js:1:10866"
arguments는 배열같아도 배열이 아니어서 map method가 없기 때문에 오류가 난다.
// from으로 arguments를 배열로 변환하여 사용
function addMark(){
let newArray = Array.from(arguments);
let newData = newArray.map(function(value){
return value + "!";
})
console.log(newData);
}
addMark(1,2,3,4,5);
>> ["1!", "2!", "3!", "4!", "5!"]
'JSTS' 카테고리의 다른 글
[JS][ES6] Arrow function, defualt parameter, rest parameter (0) | 2022.06.05 |
---|---|
[JS][ES6] Template 처리 (0) | 2022.06.05 |
[JS][ES6] set, map (0) | 2022.06.05 |
[JS][ES6] 객체, destructuring (0) | 2022.06.05 |
[JS][ES6] const, let (0) | 2022.06.05 |