티스토리 뷰
Javascript Array 내장함수 활용하기
- Array.prototype.find()
- ⇒ 조건에맞는 원소중 맨첫번째거를 리턴함
const array = [ 5, 12, 8, 130, 44, 11 ];
const found = array.find( e => e > 10 ); // 12
console.log(found); // 12
Array.prototype.find() - JavaScript | MDN
Array.prototype.find() - JavaScript | MDN
find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.
developer.mozilla.org
Array.prototype.includes()
- 배열에 원소가 들어있으면 true / 없으면 false
- ⇒ 배열이 특정요소를 포함하고 있는지를 판별
const array= [1,2,3,4];
console.log(array.includes(2)); // true
console.log(array.includes(5)); // false
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat')); // true
console.log(pets.includes('giraffe')); //false
Array.prototype.indexOf()
- ⇒ 요소의 인덱스번호를 리턴
const array = [ 2, 9, 9 ];
console.log(array.indexOf(2)); // 0
console.log(array.indexOf(9)); // 1 (첫번째 원소)
console.log(array.indexOf(9,2)); // 2 (두번째 원소)
Array.prototype.keys()
- ⇒ 배열은 인덱스번호로 Key값을 나타낸다
const array = ['a', 'b', 'c'];
const iterator = array.keys(); // Array Iterator [ 0, 1, 2 ]
// 0
// 1
// 2
for(const key of iterator) {
console.log(key);
}
- Object.keys() vs Array.keys()
- Array.keys() 는 누락된 속성이 나타나는 빈공간을 무시하지 않는다.
const array = ['a', , 'c'];
const sparseKeys = Object.keys(array); // ['0', '2']
const denseKeys = [...array.keys()]; // [0, 1, 2]
Object.keys()
- 주어진 객체의 속성 이름들로 구성된 배열로 리턴
const sampleObj = {
a: 'something',
b: 42,
c: false
}
keys = Object.keys(sampleObj);
console.log(keys); // Array ["a", "b", "c"]
Object.keys() - JavaScript | MDN
Object.keys() - JavaScript | MDN
Object.keys() 메서드는 주어진 객체의 속성 이름들을 일반적인 반복문과 동일한 순서로 순회되는 열거할 수 있는 배열로 반환합니다.
developer.mozilla.org
Object.entries()
Object.entries() static method returns an array of a given object’s own enumerable string-keyed property key-value pairs.
객체를 [ 0: key, 1: value ] 배열 형태로 분리시켜 배열로 리턴한다.
const obj = {
a: 'something',
b: 42
}
const entries = Object.entries(obj);
console.log(entries); // Array[ Array["a", "something"], Array["b", 42]]
for(const [key, value] of entries) {
console.log(`${key}: ${value}`);
}
// "a: something"
// "b: 42"
const obj = { foo: "bar", baz: 42 };
const entries = Object.entries(obj); // Array[ Array["foo", "bar"], Array["baz", 42] ]
const _map = new Map(entries);
console.log(_map);
// Map(2) { "foo" => "bar", "baz" => 42}
// 0: {"foo" => "bar"}
// 1: {"baz" => 42}
Object.entries() - JavaScript | MDN
Object.entries() - JavaScript | MDN
The Object.entries() static method returns an array of a given object's own enumerable string-keyed property key-value pairs.
developer.mozilla.org
Generator
const foo = function*() {
yield 'a';
yield 'b';
yield 'c';
};
let str = '';
for(const val of foo()) {
str = str + val;
}
console.log(str); // abc
function *generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator(); // Generator객체 {}
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
- Generator object is returned by a generator function and it conforms to both the iterable protocol and iterator protocol
- 이터러블 프로토콜과 이터레이터 프로토콜을 실행하도록한다.
- 제너레이터로 infinite 구현하기
- 제너레이터 생성자함수를 호출
- 맨처음: gen.next().value ⇒ 초기값 호출
- 2번째부터…매번 호출하면: gen.next().value ⇒ 계속 더해서 누계된 값을 호출.
- Generator.prototype.next()
function *infinite() {
let index = 0; // index 초기화
while(true) {
yield index++; // index를 증가시킨다.
}
}
const gen = infinite(); // 제너레이터를 리턴 Generator{}
console.log(gen.next().value); // 0 (초기값 index 를 리턴)
console.log(gen.next().value); // 1 (index에서 누계됨)
console.log(gen.next().value); // 2
'Backend > 꾸준히 TIL' 카테고리의 다른 글
[클린아키텍쳐] 설계원칙 SOLID 1 (1) | 2023.11.03 |
---|---|
[Github Actions] Slack-WebHook을 활용하여 PR 요청할때마다 슬랙메시지 보내주도록하기 (0) | 2023.07.06 |
[npm] dependencies 와 devDependencies 차이점 (0) | 2023.06.27 |
[에러노트] zsh: command not found: firebase (0) | 2023.06.12 |
[AWS/다큐먼트 읽기] AWS DynamoDB vs Timestream (0) | 2023.06.08 |
- Total
- Today
- Yesterday
- 참고
- nestjs jest
- MongoDB
- 바이트디그리
- 디지털디톡스
- IT용어
- TDD
- vscode
- 미완
- 클린아키텍쳐
- typeORM
- 한달독서
- node.js
- OS
- jest
- 한달어스
- 습관개선
- git
- Jekyll
- MySQL
- 개발용어
- TypeScript
- Nest.js
- nestjs
- gem
- 갓생살자
- 스마트폰중독
- RDBMS
- Mongoose
- 나도 할 수 있다
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |