concat()메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환한다.
사용방법
const array1 = ['a','b','c'];
const array2 = ['d','e','f'];
const array3 = array1.concat(array2);
console.log(array3)
//결과 : ['a', 'b', 'c', 'd', 'e', 'f']
for문 돌리는거랑 같은 개념
Array.prototype.forEach(callback[, thisArg])
callback
: function(currentValue[, index[, originalArray]])
currentValue
: 현재값index
: 현재 인덱스originalArray
: 원본배열thisArg
: this에 할당할 대상. 생략시 global객체
const a = [1, 2, 3];
a.forEach(
function (v, i, arr) {
console.log(v, i, arr, this);
},
[10, 11, 12]
);
/*
1 0 [1, 2, 3] [10, 11, 12]
2 1 [1, 2, 3] [10, 11, 12]
3 2 [1, 2, 3] [10, 11, 12]
*/
forEach()함수를 사용할 때 콜백함수로 일반 함수를 선언하는 것과 ES6에 추가된 화살표 함수를 사용하는 것에는 큰 차이점이 있다.
const fun1 = {
name: "pyh",
languages: ["java", "c++", "javascript"],
languagesPrint: function () {
console.log(this.name);
this.languages.forEach(function (language) {
console.log(language);
console.log(this);
});
},
};
fun1.languagesPrint();
/*
pyh
java
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
c++
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
javascript
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
*/
위의 코드에서 languagesPrint()의 this는 현재 객체인 fun1을 가리키지만, forEach의 인자로 들어간 콜백함수는 그렇지 않기 때문에 window객체가 나오게 된다. 이런 현상을 해결 할 수 있는 방법은 다음과 같다.
//arrow function -> forEach 내부 함수값에 있는 this고정.
const fun1 = {
name: "pyh",
languages: ["java", "c++", "javascript"],
languagesPrint: function () {
console.log(this.name);
this.languages.forEach((language) => {
console.log(this.name, language);
});
},
};
fun1.languagesPrint();
/*
pyh
pyh java
pyh c++
pyh javascript
*/
다음과 같이 콜백함수를 arrow function으로 선언해주면, forEach()를 호출하는 this와 콜백함수 내의 this는 같게 되므로, 객체 변수를 참조할 수 있게 된다.
this바인딩
- 전역공간에서 : window / global
- 함수 호출시 : window /global
- 메서드 호출시 : 메서드 호출 주체(메서드명 앞)
- callback 호출시 : 기본적으로는 함수내부에서와 동일
- 생성자함수 호출시 : 인스턴스
for문을 돌려서 새로운 배열을 만든다.
return필수
Array.prototype.map(callback[, thisArg])
callback
: function (currentValue[, index[, originalArray]])
currentValue
: 현재값index
: 현재 인덱스originalArray
: 원본 배열thisArg
: this에 할당할 대상. 생략시 global객체,window객체const a = [1, 2, 3];
const b = a.map(
function (v, i, arr) {
console.log(v, i, arr, this);
return this[0] + v;
},
[10]
);
/*
1 0 [1, 2, 3] [10]
2 1 [1, 2, 3] [10]
3 2 [1, 2, 3] [10]
*/
console.log(b); // [11,12,13]
※ map함수로 생성된 배열은 기존 배열이 아닌 새로운 배열이다.
const a = [1, 2, 3];
const b = a.map((v) => {
return v;
});
console.log(a === b); //false