const arr = [1, 2, 3];
arr[3] = 'test';
arr['propterty'] = 'string';
arr['obj'] = {};
arr[{}] = [1, 2, 3];
arr['func'] = function () {
return 'hello';
};
console.log(arr);
// [
// 1,
// 2,
// 3,
// 'test',
// propterty: 'string',
// obj: {},
// '[object Object]': [ 1, 2, 3 ],
// func: [Function (anonymous)]
// ]
// 아무런 문제 없이 정상적으로 삽입됨을 확인 할 수 있다.
console.log(typeof arr);
// object
확인할 수 있듯이, Javascript에서는 배열의 아무 위치에 아무 타입을 넣어도 오류가 발생하지 않는다.
<aside> 💡 Array.isArray()
해당 메서드는 인자가 Array인지 정확하게 파악해냅니다.
Array.isArray(obj)
obj : 검사할 객체
객체가 Array라면 true를 반환, 아니라면 false를 반환합니다.
// 모두 true 반환
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array('a', 'b', 'c', 'd'));
Array.isArray(new Array(3));
// Array.prototype은 스스로도 배열입니다
Array.isArray(Array.prototype);
// 모두 false 반환
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });
</aside>
<aside> 💡 Array.length
Array.length는 실제 길이를 보장하지 않는다.
const arr = [1, 2, 3, , , , , , 9];
console.log(arr.length);
// 4 아님
arr.length = 0;
console.log(arr);
// [] 길이 조정만으로 배열을 초기화할 수 있음
</aside>
참고 https://preamtree.tistory.com/115 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
빠르게 설명 들어간다
let arr = {
0: 'i',
1: 'am',
2: 'iron',
3: 'man',
length: 4,
};
console.log(Array.isArray(arr));
// false
다음과 같이 객체지만, 배열의 형태를 갖고 배열처럼 행동할 수 있는 객체를 유사배열객체라고 한다.
가급적이면 유사배열 객체를 만들지 않는 것이 좋다.
<aside> 💡 arguments 객체
arguments
객체는 함수에 전달된 인수에 해당하는 Array
형태의 객체입니다.
function func1() {
console.log(arguments[0]);
// expected output: 1
console.log(arguments[1]);
// expected output: 2
console.log(arguments[2]);
// expected output: 3
console.log(Array.isArray(arguments));
// false
}
func1(1, 2, 3);
임의로 매개변수를 전달하지 않았음에도 함수 내부에서 arguments객체를 통해 매개변수 값에 접근할 수 있다.
arguments 객체는 Array가 아니다. length를 제외하고는 어떠한 Array의 속성도 갖고있지 않다. 따라서 map()이나 filter()같은 고차함수를 사용할 수도 없다. 일종의 유사배열객체로써 바라볼 수 있는 것이다.
let args = Array.prototype.slice.call(arguments);
let args = [].slice.call(arguments);
let args = Array.from(arguments);
let args = [...arguments];
하지만 위와같이 arguments객체를 실제 Array로 변환할 수도 있다.
</aside>
참고 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/arguments