[JavaScript] JS_ 5. Object & Array (2)

jungeundelilahLEE·2020년 10월 5일
0

# INDEX

1. Values & Data type
2. Operators
3. Control flow
4. Scope & Hoisting
5. Object & Array
6. This
7. Prototype & Inheritance
8. Function
9. Callback function
10. Closuer
11. Class
12. Others

해당 포스팅은 MDN의 내용을 참고하였습니다

5. Object & Array (2)

5-1. 다양한 Array methods

  • 유사배열은 객체의 메소드를 사용할 수 없음

Array.from( )

: 유사 배열 객체(array-like object) or 반복 가능한 객체(iterable object)를 얕게 복사해 새로운 Array 객체를 만듦

- 유사배열객체 : length속성을 가진 객체
- 반복 가능한 객체 : Map,Set 등 객체의 요소를 얻을 수 있는 객체
Array.from (arrayLike [, mapFn [, thisArg]] )
arrayLike : 배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체
mapFn(opt) : 배열의 모든 요소에 대해 호출할 맵핑 함수
thisArg(opt) : mapFn 실행 시에 this로 사용할 값
return : 새로운 Array 인스턴스
Array.from('foo'); 		// ["f", "o", "o"]
------------------------------------------
const foo = new Set(['foo', window]); 
Array.from(foo);		// ["foo", window]
------------------------------------------
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());	// ['a', 'b'];

Array.isArray()

: 인자가 Array인지 "판별"

Array.isArray (obj)
obj : 판별할 객체
return : if 객체가 Array이면 true, 아니면 false
return true ex)
Array.isArray(new Array('a', 'b', 'c', 'd'));
Array.isArray(new Array(3));
Array.isArray(Array.prototype);
------------------------------------------
return false ex)
Array.isArray();

Array.of()

: 인자의 수나 유형에 관계없이 가변 인자를 갖는 새 Array 인스턴스를 만듦

Array.of (element0 [, element1 [, ... [, elementN] ] ] )
elementN : 배열을 생성할 때 사용할 요소
return : 새로운 Array 객체
Array.of(1);         // [1]
Array.of(1, 2, 3);   // [1, 2, 3]
Array.of(undefined); // [undefined]

Array.prototype.concat()

: 인자로 주어진 배열이나 값을, "기존 배열에 합쳐서 새 배열"을 반환

- 메소드를 호출한 "배열(배열이 아닐 경우 error)" 뒤에, 각 인수를 "순서대로" 붙임
- 배열이나 값을 이어붙여도 원본은 변하지 않음
array.concat ( [value1 [, value2 [, ... [, valueN] ] ] ] )
매개변수 : 배열 or 값
valu1..valueN 인자를 생략하면 기존배열의 얕은 복사본을 반환함
return : 새로운 Array 객체
let num1 = [1];
let num2 = {name : "willy"}
let num3 = [7, 8, 9];
let add1 = num1.concat();
  console.log(d)		// [1]
let add2 = [num1[0]].concat(num2);
  console.log(e)		// [1, {name: "willy"}]
  console.log(add2[1])		// [object Object] {name: "willy"}

Array.prototype.filter()

: 주어진 함수의 테스트를 통과하는 모든 요소를 모아 "새로운 배열"로 반환

arr.filter ( callback ( element [, index [, array]] ) [, thisArg] )
callback : 각 요소를 테스트할 함수 / true를 반환하면 요소 유지, false를 반환하면 종료 / 아래 세 가지 매개변수를 받음
element : 처리할 현재 요소
index(opt) : 처리할 현재 요소의 인덱스
array (opt) : filter를 호출한 배열
thisArg (opt) : callback을 실행할 때 this로 사용하는 값
return : 테스트를 통과한 요소만으로 이루어진 새로운 배열 / 어떤 요소도 테스트를 통과하지 못하면, 빈 배열을 반환
function isBigEnough(value) {
  return typeof value === "boolean";
}
let filtered = [1,2,3,true, {name:"willy"}]
let result = filtered.filter(isBigEnough);
  console.log(result);		// [true]

Array.prototype.forEach()

: 주어진 함수를 배열 요소 "각각에 대해" 실행

- 주어진 callback을 배열에 있는 각 요소에 대해 오름차순으로 한번씩 실행함
- map()과 reduce()와는 달리 undefined를 반환
- 예외를 두는 경우를 제외하고는, forEach()를 중간에 멈출 수 없음
- for문, for of, for in, every(), some(), find(), findIndex() 를 통해 반복을 종료시킬 수 있음
arr.forEach ( callback ( currentvalue [, index [, array] ] ) [, thisArg] )
callback : 각 요소에 대해 실행할 함수 / 아래 세 가지 매개변수를 받음
currentValue : 처리할 현재 요소
index (opt) : 처리할 현재 요소의 인덱스
array (opt) : forEach()를 호출한 배열
thisArg (opt) : callback을 실행할 때 this로 사용할 값
return : undefined
  • keys(), entries(), every(), some(), values() 검색해보기
let items = ['item1', 'item2', 'item3'];
let copy = [];
// for문 사용 ex)
for (let i=0; i<items.length; i++) {
  copy.push(items[i]);
}
// forEach 사용 ex)
items.forEach(function(item){
  copy.push(item);
  console.log(items); 	// ["item1", "item2", "item3"]
  			// ["item1", "item2", "item3"]
  			// ["item1", "item2", "item3"]
});
console.log(copy); 	// ["item1", "item2", "item3"]

Array.prototype.includes()

: 배열이 특정 요소를 포함하고 있는지 "판별"

arr.includes ( valueToFind [, fromIndex] )
valueToFind : 탐색할 요소
   - 문자열을 비교할 때, 대소문자를 구분함
fromIndex (opt) : 해당 배열에서 searchElement 검색을 시작할 위치
  - 0이 기본값
  - 음수일 경우 : array.length + fromIndex의 인덱스
  - 계산된 인덱스가 -1 * array.length 보다 작거나 같다면, 전체 배열이 검색됨
  - fromIndex 가 배열의 길이와 같거나 크면, false 를 반환
return : Boolean
[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(3, 3);  // false (같거나 큰 경우)
[1, 2, 3].includes(3, -1); // true (음수의 경우 : 3 + (-1) === 2 )
[1, 2, 3].includes(3, -1) === [1, 2, 3].includes(3, 2);	// true
['a', 'b', 'c'].includes("a", -100)// true (계산된 인덱스가 -1*array.length와 같거나 더 작은 경우)
['a', 'b', 'c'].includes("a", -2); // false

Array.prototype.indexOf()

: 배열에서 "지정된 요소"를 찾을 수 있는 "첫번째 인덱스"를 반환 / 존재하지 않으면 -1을 반환

- ===을 사용하여 검색 요소를 Array의 요소와 비교 (strict)
arr.indexOf ( searchElement [, fromIndex ] )
searchElement : 배열에서 찾을 요소
fromIndex Optional : 검색을 시작할 인덱스
  - 인덱스가 배열의 길이와 같거나 큰 경우 -1이 반환되므로 배열이 검색되지 않음
  - 제공된 인덱스가 음수이면 배열은 앞에서 뒤로 검색
  - 계산 된 인덱스가 0보다 작으면 전체 배열이 검색됨
  - 기본값 : 0 (기본값의 경우, 전체 배열을 검색함)
return : 배열 내 요소의 첫번째 인덱스값 / 없으면 -1
let array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
------------------------------------------
function updateVegetablesCollection (veggies, veggie) {
    if (veggies.indexOf(veggie) === -1) {
        veggies.push(veggie);
        console.log('새로운 veggies 컬렉션 : ' + veggies);
    } else if (veggies.indexOf(veggie) > -1) {
        console.log(veggie + ' 은 이미 veggies 컬렉션에 존재합니다.');
    }
}
let veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
updateVegetablesCollection(veggies, 'spinach'); 
		// 새로운 veggies 컬렉션 : potato, tomato, chillies, green-pepper, spinach
updateVegetablesCollection(veggies, 'spinach'); 
		// spinach 은 이미 veggies 컬렉션에 존재합니다.

Array.prototype.join()

: 배열의 모든 요소를 연결해 "하나의 문자열"로 만듦

- 모든 배열 요소가 문자열로 변환된 다음 하나의 문자열로 연결됨
- 요소가 undefined 또는 null이면 빈 문자열로 변환
arr.join ( [ separator ] )
separator (opt) : 배열의 각 요소를 구분할 문자열을 지정
return : 배열의 모든 요소들을 연결한 하나의 문자열을 반환 / if (arr.length===0)일 경우, 빈 문자열을 반환
let baby = ["willy", "is", "so", "cute"];
console.log(baby.join());	// "willy,is,so,cute"
console.log(baby.join(""));	// "willyissocute"
console.log(baby.join("-"));	// "willy-is-so-cute"

Array.prototype.map()

배열 내의 "모든 요소 각각"에 대하여 주어진 함수를 호출한 결과를 모아 "새로운 배열"을 반환

arr.map ( callback ( currentValue [, index [, array] ] ) [, thisArg] )
callback : 새로운 배열 요소를 생성하는 함수 / 아래 세 가지 인수를 가질 수 있음
    - currentValue : 처리할 현재 요소
    - index (opt) : 처리할 현재 요소의 인덱스
    - array (opt) : map()을 호출한 배열
thisArg Optional : callback을 실행할 때 this로 사용되는 값
return : 배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열
let number = [1, 4, 9];
let doubles = number.map(function(num) {
  return num * 2;
});
console.log(doubles);	// [2, 8, 18]
console.log(number);	// [1, 4, 9] (원본 배열 유지)
---------------------------------------------
let array = [{key:1, value:10},
             {key:2, value:20},
             {key:3, value: 30}];

let reformattedArray = array.map(function(obj){ 
   let newObj = {};
   newObj[obj.key] = obj.value;
   return newObj;
});
console.log(reformattedArray); 	// [{1:10}, {2:20}, {3:30}]

Array.prototype.pop()

: 배열에서 "마지막 요소를 제거하고 그 요소"를 반환 / 원본 배열 변경 O

arr.pop()
return : 배열에서 제거한 요소 / 빈 배열의 경우, undefined
let name = ["jung", "eun", "lee"];
console.log(name.pop());	// "lee"
console.log(name);		// ["jung", "eun"]

Array.prototype.push()

: 배열의 "마지막"에 하나 이상의 "요소를 추가"하고, 배열의 새로운 길이를 반환 / 원본 배열 변경 O

arr.push ( element1 [, ...[, elementN] ] )
elementN : 배열의 끝에 추가할 요소
return : 호출한 배열의 새로운 length 속성
let baby = ["willy"];
let add = baby.push("is", 2, "years old")
console.log(add);	// 4
console.log(baby);	// ["willy", "is", 2, "years old"]

Array.prototype.shift()

배열에서 "첫번째 요소를 제거"하고, "제거된 요소를 반환" / 원본 배열 변경 O

arr.shift ( )
return : 배열에서 제거한 요소 / 빈 배열의 경우, undefined

Array.prototype.unshift()

: 새로운 요소를 배열의 "첫번째 요소로 추가" / 원본 배열 변경 O

arr.unshift ( [...elementN] )
elementN : 배열 맨 앞에 추가할 요소
return : 메서드를 호출한 배열의 새로운 length 속성

Array.prototype.reverse()

: 배열의 "순서를 반전"

Array.prototype.slice()

: 떤 배열의 "begin부터 end까지(end 미포함)에 대한 얕은 복사본"을 새로운 배열 객체로 반환 / 원본 배열 변경 X

Array.prototype.splice()

: 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경


Math.abs(x) : x의 절대값

  • 빈 객체, 하나 이상의 요소를 가진 배열, 숫자가 아닌 문자열, undefined나 빈 매개변수를 받으면 NaN을 반환
  • null, 빈 문자열이나 빈 배열을 제공하면 0을 반환

Math.ceil(x) : x 이상의 가장 작은 정수

  • Math.ceil(4.04) // 5
    Math.ceil(4) // 4

Math.floor(x) : x 이하의 가장 큰 정수

  • Math.floor(4.04) // 4
    Math.floor(4) // 4

Math.max(x, y, z ..) : 입력된 숫자들 중 가장 큰 숫자를 반환

  • 하나라도 숫자가 아닐 경우, NaN
  • 매개변수가 없을 경우, Infinity

Math.min(x, y, z ..) : 입력된 숫자들 중 가장 작은 숫자를 반환

  • 하나라도 숫자가 아닐 경우, NaN
  • 매개변수가 없을 경우, Infinity

Math.round(x) : x를 반올림한 값과 가장 가까운 정수

Math.random( ) : 0 이상 1 미만의 구간에서 근사적으로 균일한 부동소숫점 의사난수를 반환

Math.sqrt(x) : x에 루트(√ )를 씌운 제곱근

  • 매개변수가 음수일 경우, NaN

Math.cbrt(x) : x의 세제곱근

profile
delilah's journey

0개의 댓글