1. 배열과 객체 생성
> 동일한 출력값을 보여준다.
//배열 생성
const toolArray = ['html', 'css', 'js'];
//1. 출력
console.log(toolArray[0]); // 출력값 : html
console.log(toolArray[1]); // 출력값 : css
console.log(toolArray[2]); // 출력값 : js
//객체 생성
const tollObj = {
'0' : 'html',
'1' : 'css',
'2' : 'js'
}
console.log(tollObj[0]); // 출력값 : html
console.log(tollObj[1]); // 출력값 : css
console.log(tollObj[2]); // 출력값 : js
2. typeof 연산자 비교
> typeof 연산 결과는 배열과 객체 모두 object다.
//2. typeof 연산자 비교
console.log(typeof toolArray); //출력값 object
console.log(typeof toolObj); //출력값 object
3. length 프로퍼티
> 객체는 length 프로퍼티가 존재하지 않는다. 따라서 toolObj.length의 결과는 undefinedr가 나온다.
//3. length 프로퍼티
console.log(toolArray.length); //출력값 3
console.log(toolObj.length); //출력값 undefined
4. 배열 표준 메서드 호출 여부
> 객체는 배열이 아니므로 push() 와 같은 표준 배열 메서드를 사용할 수 없다.
이것은 배열과 객체가 자신의 부모인 프로토타입 객체가 서로 다르기 때문이다.
객체 리터럴 방식으로 생성한 객체는 Object.prototype 객체가 프로토 타입이다.
배열의 경우에는 Array.prototype 객체가 부모 객체인 프로토타입이 된다.
Array.prototype 에는 pop(), push() 와 같은 표준 배열 메서드가 포함되어 있다.
Array.prototype 객체의 프로토타입은 Object.prototype 객체여서 2가지의 포함된 표준 메서드들을 모두 사용할 수 있다.
*관계도
[객체 프로토타입]
객체 → Object.prototype
[배열 프로토타입]
객체 → Array.prototype → Object.prototype
// 4. 배열 표준 메서드
toolArray.push('react');
for (var i=0; i<toolArray.length; i++) {
console.log(toolArray[i]) //['html', 'css', 'js', 'react']
}
toolObj.push('react');
console.log(toolObj) //Uncaught TypeError : Object #<Object> has no method 'push'
[출처 : 고현준,송형주 ,인사이드 자바스립트]
See the Pen Untitled by 조민혁 (@iqgzrljw-the-typescripter) on CodePen.
'JS' 카테고리의 다른 글
[JavaScript] 비동기와 콜백 함수 (0) | 2023.08.01 |
---|---|
[JavaScript] async & await (0) | 2023.08.01 |
[React] Hooks - useContext (0) | 2023.07.31 |
[JS] wScratchPad.js 사용하기 (0) | 2023.07.11 |
[JS] input[type="range"] 별점 드래그 (0) | 2023.07.07 |