개발

[Javascript] 객체, 배열 정리

ash_ 2023. 5. 8. 09:56

배열

  • push, pop, shift, unshift
let arr = new Array();
let arr_1 = new Array(5); // empty array 5

let arr2 = [];

arr.push('a'); // 맨 뒤에 추가
arr.push(1);
arr.push({name: 'hello'});
arr.unshift(10); // 맨 앞에 추가

arr.pop(); // 맨 뒤
arr.shift(); // 맨 앞
  • splice, slice
arr.splice(2,1,6,7,8); // 인덱스 2부터 1개 삭제, 그 자리에 6,7,8 추가
arr.splice(3); // 인덱스 3부터 끝까지 삭제, 삭제한 배열 리턴

let newArr = arr.slice(1, 4); // 인덱스 1~3 요소를 newArr에 생성, 원본배열 변경안함
  • contact
// 원본 배열 생성
let myArray1 = [1, 2, 3];
let myArray2 = [4, 5, 6];
let myArray3 = [7, 8, 9];

// 3개의 배열을 병합하여 새로운 배열 생성
let newArray = myArray1.concat(myArray2, myArray3);
console.log(newArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

// contact() 함수는 원본 배열을 변경하지 않음
console.log(myArray1); // [1, 2, 3]
console.log(myArray2); // [4, 5, 6]
console.log(myArray3); // [7, 8, 9]
  • indexOf
arr.indexOf('apple') // apple 의 처음 인덱스 반환
arr.lastIndexOf('apple') // apple 의 마지막 인덱스 반환
// 요소 없으면 둘다 -1 반환
  • find, findIndex, includes
arr.find((ele) => ele === 'yellow') // 조건을 만족하는 첫번째 요소 반환
arr.findIndex((ele) => ele === 'red') // 조건을 만족하는 첫번째 요소의 인덱스 반환

arr.includes('blue') // 특정 요소 있는지 boolean값으로 확인
  • map, sort, reverse
let newArr = arr.map((num)=> num * num); // arr의 요소들 제곱한 수가 newArrr에 담김
arr.sort() // 문자열로 정렬
arr.reverse() // 배열 뒤집기
  • filter, reduce, split, join
let evenArr = arr.filter((num)=> num%2===0); // 짝수인 요소만 evenArr에 추출하여 저장

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// accumulator 는 누적된 수, currentValue는 현재 값. 모든 값을 더하는 함수, 두번째 인자는 초기값

const newWords = strArr.split(';'); // 문자열을 ; 를 구분자로 나눈 배열 생성
const str = newWords.join(';') // 다시 ;를 넣고 문자열 생성
const numbers = [3, 8, 2, 10, 5];
const max = numbers.reduce((accumulator, currentValue) => {
  return Math.max(accumulator, currentValue);
}, -Infinity); // 최소값 구하는 reduce 예제
  • 배열 분산
let copy = [...arr]; // arr를 펼쳐서 복사해넣음. 원래 copy에 요소가 있었다면 뒤에 붙여 넣음.(스프레드 문법))
const [a, b, ...c] = arr; // arr의 값을 a에 하나, b에 하나, 나머지를 c에 넣기

객체

객체l는 참조값(레퍼런스)

let newKey = 'zzz';
let newValue = 'vvv';

let person = {
	'first name' : 'Max', // 문자열로 키값 가능
	age: 30,
	hobbies: ['Sports', 'Coding'],
	greet: function () { alert('hello'); }, // 함수 가능
	1.5: 'wowoo', // 숫자 키값 가능, 양의 정수, 음수 안됨, 소수 가능
	[newKey]: newValue, // 동적 키밸류
};

person.isAdmin = true; // 바로 프로퍼티와 값 추가 가능
delete person.age; // undefined 로 바뀜, 삭제

console.log(person['first name']);
console.log(person['isAdmin']); // [] 로 접근할땐 안에 '' 문자열로
console.log(person[1.5]); // 숫자는 문자열로 감쌀 필요 없음(감싸도 됨)
console.log(person[newKey]); // 동적 key 접근

for (key in person) {
  console.log(key);
  if (key == `${newKey}`)
    console.log(">>>", person[`${newKey}`]);
  if (key == 'hobbies')
    console.log('[[[', person[key], ']]]');
}

if ('age' in person) // false
	console.log(person.age);
if (person.age === undefined)
	console.log("where is age???");
const newPerson = person;
person.age = 30;
console.log(newPerson.age) // 30, person 바뀌면 같이 바뀜. 레퍼런스니까!

const diffPerson = {...person} // 이러면 깊은복사로 다른 객체가 됨
// 하지만 hobbies 배열은 그대로 레퍼런스이기 때문에 아직 연결되어있음!

const diffPerson = {...person, hobbies: [...person.hobbies]}
// 이렇게 해줘야 배열까지 깊은복사 됨!
  • assign()
const person = {
  name: 'John',
  age: 30
};

const employee = {
  jobTitle: 'Software Engineer',
  location: 'San Francisco'
};

const merged = Object.assign(person, employee);
console.log(merged); // {name: "John", age: 30, jobTitle: "Software Engineer", location: "San Francisco"}
console.log(person); // {name: "John", age: 30, jobTitle: "Software Engineer", location: "San Francisco"}

// 얕은복사이기 때문에 레퍼런스 주소값 넘어옴! 바뀌면 복사된 값도 바뀜

this

함수가 실행될 때, 해당 함수 내에서 참조하는 객체를 가리키는 예약어

메소드를 객체에서 분리하여 다른 변수에 할당하면 전역객체 참조

const myObj = {
  name: 'John',
  greet: function () {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const greet = myObj.greet;
myObj.greet(); // Hello, my name is John
greet(); // Hello, my name is undefined

//bind 사용하여 this 가 항상 myObj를 참조하도록 하기
const greet2 = myObj.greet.bind(myObj);
greet2(); // Hello, my name is John
  • apply(), call() this 를 명시적으로 지정함
const obj = { name: 'John' };

function sayHi(greeting) {
  console.log(`${greeting}, my name is ${this.name}`);
}

sayHi.call(obj, 'Hello'); // 출력: Hello, my name is John
const obj = { name: 'John' };

function sayHi(greeting, punctuation) {
  console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}

sayHi.apply(obj, ['Hello', '!']); // 출력: Hello, my name is John!

apply는 인수가 배열로 전달됨.

  • bind() 와 차이점

**call()**과 **apply()**는 함수를 즉시 호출하면서 **this**를 지정합니다. **call()**과 **apply()**는 첫 번째 매개변수로 **this**로 지정할 객체를 받고, 이어지는 매개변수는 함수 호출에 사용될 인수를 나타냅니다.

**bind()**는 함수를 호출하지 않고 **this**가 지정된 새로운 함수를 반환합니다. 이렇게 반환된 함수를 나중에 호출할 수 있습니다. bind() 메소드는 첫 번째 매개변수로 **this**로 지정할 객체를 받으며, 이후에 호출될 함수에 전달되는 인수를 나타내는 매개변수를 받습니다.

보통 this는 (함수 내부에서 사용되는 경우) 함수를 호출한 '무언가'를 나타냅니다. 이는 전역 컨텍스트, 객체 또는 바인딩된 데이터/객체일 수도 있습니다(예: 브라우저가 클릭 이벤트를 트리거한 버튼과 this를 바인드할 때).

1) 전역 컨텍스트(즉 함수 외부)에서의  this

function something() { ... }
console.log(this); 
// 전역 객체(브라우저의 창)를 기록합니다 - 항상(엄격 모드에서도)!

2) (화살표 함수가 아닌)함수에서의 this - 전역 컨텍스트에서 호출됐을 때

function something() { console.log(this);}
something(); 
// 엄격 모드가 아닐 땐 전역 객체(브라우저의 창)를 기록하고 엄격모드일 땐 undefined

3) 화살표 함수에서의 this - 전역 컨텍스트에서 호출됐을 때

const something = () => { console.log(this);}
something(); // 전역 객체(브라우저의 창)를 기록합니다 - 항상(엄격 모드에서도)!

4) (화살표가 아닌) 메서드에서의 this - 객체에서 호출됐을 때

const person = { 
	name: 'Max',
	greet: function() { // or use method shorthand: greet() { ... }
	console.log(this.name);
	}
};
person.greet(); // 'Max'를 기록하고, "this"는 person 객체를 참조함

5) (화살표 함수) 메서드에서의 this - 객체에서 호출됐을 때

const person = { 
	name: 'Max',
	greet: () => {
		console.log(this.name);
	}
};
person.greet(); // 아무것도 기록하지 않음(아니면 창 객체의 일부 전역 이름을 기록), "this"는 엄격 모드에서도 전역(창) 객체를 나타냅니다.

this는 다른 객체에서 호출하는 경우 예상치 못한 것을 나타낼 수도 있습니다.

const person = { 
	name: 'Max',
	greet() {
		console.log(this.name);
	}
};

const anotherPerson = { name: 'Manuel' }; // 내장된 greet 메서드가 없습니다!
anotherPerson.sayHi = person.greet; // greet은 여기서 호출되는 것이 아니라 "anotherPerson" 객체의 새로운 프로퍼티/메서드에 할당됩니다.
anotherPerson.sayHi(); // "anotherPerson" 객체에서 호출되었기 때문에 ‘Manuel’을 기록합니다 => "this"는 호출한 "무언가"를 나타냅니다
  • getter, setter
let date = new Date();
const person = {
  name: 'Max',
  greet: () => {
    console.log(this.name);
  },

  set age(birth) {
    this._age = date.getFullYear() - birth;
  },
  get age() {
    return this._age + 1
  }
};

getter, setter 를 사용하여 조건을 추가할 수 있음

'개발' 카테고리의 다른 글

[자료구조] 힙(Heap)  (1) 2024.02.01
[자료구조] 트리  (0) 2024.02.01
[자료구조] 그래프  (0) 2024.02.01
[크롬 브라우저 하드웨어 가속] Udemy 화면 재생 안될 때  (0) 2023.05.08
[Git] git reset vs revert  (0) 2023.03.28