Array.prototype.entries()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Phương thức entries() của các instance Array trả về một đối tượng iterator mảng mới chứa các cặp khóa/giá trị cho mỗi chỉ số trong mảng.

Try it

const array = ["a", "b", "c"];

const iterator = array.entries();

console.log(iterator.next().value);
// Expected output: Array [0, "a"]

console.log(iterator.next().value);
// Expected output: Array [1, "b"]

Syntax

js
entries()

Parameters

Không có.

Return value

Một đối tượng iterator có thể lặp (iterable iterator object) mới.

Description

Khi dùng trên mảng thưa (sparse arrays), phương thức entries() lặp qua các slot rỗng như thể chúng có giá trị undefined.

Phương thức entries()generic. Nó chỉ yêu cầu giá trị this có thuộc tính length và các thuộc tính có khóa là số nguyên.

Examples

Lặp với chỉ số và phần tử

js
const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}

// 0 'a'
// 1 'b'
// 2 'c'

Dùng vòng lặp for...of

js
const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']

Lặp qua mảng thưa

entries() sẽ duyệt qua các slot rỗng như thể chúng là undefined.

js
for (const element of [, "a"].entries()) {
  console.log(element);
}
// [0, undefined]
// [1, 'a']

Gọi entries() trên các đối tượng không phải mảng

Phương thức entries() đọc thuộc tính length của this và sau đó truy cập từng thuộc tính có khóa là số nguyên không âm nhỏ hơn length.

js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: "d", // ignored by entries() since length is 3
};
for (const entry of Array.prototype.entries.call(arrayLike)) {
  console.log(entry);
}
// [ 0, 'a' ]
// [ 1, 'b' ]
// [ 2, 'c' ]

Specifications

Specification
ECMAScript® 2027 Language Specification
# sec-array.prototype.entries

Browser compatibility

See also