Array.prototype.keys()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since May 2018.
시도해보기
const array1 = ["a", "b", "c"];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
// Expected output: 0
// Expected output: 1
// Expected output: 2
구문
js
keys()
매개변수
없음.
반환 값
새로운 순회 가능 반복자 객체
설명
예제
희소 배열에 keys() 사용하기
배열에 실제로 존재하는 키만 포함하는 Object.keys()
와 달리, keys()
반복자는 누락된 속성을 나타내는 빈 공간을 무시하지 않습니다.
js
const arr = ["a", , "c"];
const sparseKeys = Object.keys(arr);
const denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys); // [0, 1, 2]
배열이 아닌 객체에 keys() 호출하기
keys()
메서드는 this
의 length
속성을 읽은 다음, 0과 length - 1
사이의 모든 정수 인덱스를 산출합니다. 실제 인덱스 접근은 발생하지 않습니다.
js
const arrayLike = {
length: 3,
};
for (const entry of Array.prototype.keys.call(arrayLike)) {
console.log(entry);
}
// 0
// 1
// 2
명세서
Specification |
---|
ECMAScript® 2025 Language Specification # sec-array.prototype.keys |
브라우저 호환성
BCD tables only load in the browser