Hướng dẫn how to get index of element in foreach javascript - cách lấy chỉ mục của phần tử trong foreach javascript

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
3 lặp lại tên thuộc tính, không phải giá trị và làm như vậy theo thứ tự không xác định (vâng, ngay cả sau ES6). Bạn không nên sử dụng nó để lặp lại các mảng. Đối với họ, có phương thức ES5 ES5 ____ ____14 chuyển cả giá trị và chỉ mục cho chức năng bạn cung cấp:

var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32

Hoặc ES6, ____ ____, hiện có hỗ trợ trên các phiên bản trình duyệt hiện tại:

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}

Đối với Iterables nói chung (nơi bạn sẽ sử dụng vòng lặp

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
6 chứ không phải là
for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
3), tuy nhiên, không có gì tích hợp, tuy nhiên: Tuy nhiên:

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}

thử nghiệm

Nếu bạn thực sự có nghĩa là

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
3 - liệt kê các thuộc tính - bạn sẽ cần một bộ đếm bổ sung.
for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
9 có thể hoạt động, nhưng nó chỉ bao gồm các thuộc tính riêng;
for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
3 bao gồm các thuộc tính có thể suy giảm ở bất cứ đâu trên chuỗi nguyên mẫu.

Phương thức

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 thực thi một hàm được cung cấp một lần cho mỗi phần tử mảng.
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1
method executes a provided function once for each array element.

Thử nó

Cú pháp

// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)

Thông số

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2

Chức năng để thực thi trên mỗi phần tử.

Hàm được gọi với các đối số sau:

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
3

Phần tử hiện tại được xử lý trong mảng.

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
4

Chỉ số của

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
3 trong mảng.

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
6

Mảng

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 đã được yêu cầu.

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
8 Tùy chọnOptional

Giá trị để sử dụng là

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9 khi thực hiện
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2.

Giá trị trả về

// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)
1.

Sự mô tả

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 gọi hàm
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2 được cung cấp một lần cho mỗi phần tử trong một mảng theo thứ tự chỉ mục tăng dần.

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2 chỉ được gọi cho các chỉ mục mảng có giá trị được gán. Nó không được gọi cho các khe trống trong các mảng thưa thớt.

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2 được gọi với ba đối số:

  1. giá trị của phần tử
  2. chỉ mục của phần tử
  3. đối tượng mảng đang đi qua

Nếu tham số

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
8 được cung cấp cho
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1, nó sẽ được sử dụng làm giá trị
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9 của Callback. Giá trị
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
8 cuối cùng có thể quan sát được bởi
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2 được xác định theo các quy tắc thông thường để xác định
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9 được nhìn thấy bởi một hàm.

Phạm vi của các phần tử được xử lý bởi

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 được đặt trước khi gọi đầu tiên của
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2. Các yếu tố được gán cho các chỉ mục đã được truy cập hoặc các chỉ mục bên ngoài phạm vi, sẽ không được truy cập bởi
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2. Nếu các phần tử hiện tại của mảng bị thay đổi hoặc xóa, giá trị của chúng được chuyển đến
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2 sẽ là giá trị tại thời điểm
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 truy cập chúng; Các yếu tố bị xóa trước khi được truy cập không được truy cập. Nếu các yếu tố đã được truy cập được xóa (ví dụ: sử dụng
const ratings = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;

ratings.forEach(async (rating) => {
  sum = await sumFunction(sum, rating);
});

console.log(sum);
// Naively expected output: 14
// Actual output: 0
7) trong quá trình lặp, các phần tử sau sẽ bị bỏ qua. (Xem ví dụ này, bên dưới.)

CẢNH BÁO: Sửa đổi đồng thời loại được mô tả trong đoạn trước thường xuyên dẫn đến mã khó hiểu và thường phải tránh (ngoại trừ trong các trường hợp đặc biệt). Concurrent modification of the kind described in the previous paragraph frequently leads to hard-to-understand code and is generally to be avoided (except in special cases).

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 thực thi hàm
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2 một lần cho mỗi phần tử mảng; Không giống như
const arraySparse = [1, 3, /* empty */, 7];
let numCallbackRuns = 0;

arraySparse.forEach((element) => {
  console.log({ element });
  numCallbackRuns++;
});

console.log({ numCallbackRuns });

// { element: 1 }
// { element: 3 }
// { element: 7 }
// { numCallbackRuns: 3 }
0 hoặc
const arraySparse = [1, 3, /* empty */, 7];
let numCallbackRuns = 0;

arraySparse.forEach((element) => {
  console.log({ element });
  numCallbackRuns++;
});

console.log({ numCallbackRuns });

// { element: 1 }
// { element: 3 }
// { element: 7 }
// { numCallbackRuns: 3 }
1, nó luôn trả về giá trị
// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)
1 và không thể xích. Trường hợp sử dụng điển hình là thực hiện các tác dụng phụ ở cuối chuỗi.

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 không làm biến đổi mảng mà nó được gọi là. (Tuy nhiên,
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
2 có thể làm như vậy)

Phương pháp

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 là chung chung. Nó chỉ mong đợi giá trị
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9 sẽ có thuộc tính
const arraySparse = [1, 3, /* empty */, 7];
let numCallbackRuns = 0;

arraySparse.forEach((element) => {
  console.log({ element });
  numCallbackRuns++;
});

console.log({ numCallbackRuns });

// { element: 1 }
// { element: 3 }
// { element: 7 }
// { numCallbackRuns: 3 }
7 và các thuộc tính được khóa.

Lưu ý:

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
4 mong đợi một hàm đồng bộ.
for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
4 expects a synchronous function.

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
4 không chờ đợi lời hứa. Hãy chắc chắn rằng bạn nhận thức được các hàm ý trong khi sử dụng các lời hứa (hoặc các hàm async) như
for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
4 gọi lại.

const ratings = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;

ratings.forEach(async (rating) => {
  sum = await sumFunction(sum, rating);
});

console.log(sum);
// Naively expected output: 14
// Actual output: 0

Ví dụ

Sử dụng foreach () trên các mảng thưa thớt

const arraySparse = [1, 3, /* empty */, 7];
let numCallbackRuns = 0;

arraySparse.forEach((element) => {
  console.log({ element });
  numCallbackRuns++;
});

console.log({ numCallbackRuns });

// { element: 1 }
// { element: 3 }
// { element: 7 }
// { numCallbackRuns: 3 }

Hàm gọi lại không được gọi cho giá trị còn thiếu tại INDEX 2.

Chuyển đổi một vòng lặp thành foreach

const items = ['item1', 'item2', 'item3'];
const copyItems = [];

// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i]);
}

// after
items.forEach((item) => {
  copyItems.push(item);
});

In nội dung của một mảng

Lưu ý: Để hiển thị nội dung của một mảng trong bảng điều khiển, bạn có thể sử dụng

const items = ['item1', 'item2', 'item3'];
const copyItems = [];

// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i]);
}

// after
items.forEach((item) => {
  copyItems.push(item);
});
1, in phiên bản được định dạng của mảng. In order to display the content of an array in the console, you can use
const items = ['item1', 'item2', 'item3'];
const copyItems = [];

// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i]);
}

// after
items.forEach((item) => {
  copyItems.push(item);
});
1, which prints a formatted version of the array.

Ví dụ sau đây minh họa một cách tiếp cận thay thế, sử dụng

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1.

Mã sau ghi một dòng cho mỗi phần tử trong một mảng:

const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

Sử dụng này

Ví dụ sau (giả định) cập nhật các thuộc tính của một đối tượng từ mỗi mục trong mảng:

class Counter {
  constructor() {
    this.sum = 0;
    this.count = 0;
  }
  add(array) {
    // Only function expressions will have its own this binding
    array.forEach(function countEntry(entry) {
      this.sum += entry;
      ++this.count;
    }, this);
  }
}

const obj = new Counter();
obj.add([2, 5, 9]);
console.log(obj.count); // 3
console.log(obj.sum); // 16

Vì tham số

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
8 (
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9) được cung cấp cho
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1, nó được chuyển sang
const items = ['item1', 'item2', 'item3'];
const copyItems = [];

// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i]);
}

// after
items.forEach((item) => {
  copyItems.push(item);
});
6 mỗi khi nó được gọi. Cuộc gọi lại sử dụng nó làm giá trị
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9 của nó.

LƯU Ý: Nếu truyền hàm gọi lại đã sử dụng biểu thức chức năng mũi tên, tham số

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
8 có thể được bỏ qua, vì tất cả các hàm mũi tên liên kết một cách đơn giản giá trị
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9.
If passing the callback function used an arrow function expression, the
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
8 parameter could be omitted, since all arrow functions lexically bind the
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9 value.

Một hàm sao chép đối tượng

Mã sau đây tạo ra một bản sao của một đối tượng nhất định.

Có nhiều cách khác nhau để tạo một bản sao của một đối tượng. Sau đây chỉ là một cách và được trình bày để giải thích cách

const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
0 hoạt động bằng cách sử dụng các chức năng tiện ích
const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
1.

const copy = (obj) => {
  const copy = Object.create(Object.getPrototypeOf(obj));
  const propNames = Object.getOwnPropertyNames(obj);
  propNames.forEach((name) => {
    const desc = Object.getOwnPropertyDescriptor(obj, name);
    Object.defineProperty(copy, name, desc);
  });
  return copy;
};

const obj1 = { a: 1, b: 2 };
const obj2 = copy(obj1); // obj2 looks like obj1 now

Sửa đổi mảng trong quá trình lặp

Ví dụ sau đây nhật ký

const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
2,
const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
3,
const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
4.

Khi mục nhập chứa giá trị

const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
3 đạt được, mục nhập đầu tiên của toàn bộ mảng được chuyển khỏi các kết quả trong tất cả các mục còn lại di chuyển lên một vị trí. Bởi vì phần tử
const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
4 hiện đang ở vị trí sớm hơn trong mảng,
const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
7 sẽ bị bỏ qua.

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 không tạo một bản sao của mảng trước khi lặp lại.

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
0

Làm phẳng một mảng

Ví dụ sau đây chỉ ở đây cho mục đích học tập. Nếu bạn muốn làm phẳng một mảng bằng các phương thức tích hợp, bạn có thể sử dụng

const logArrayElements = (element, index /*, array */) => {
  console.log(`a[${index}] = ${element}`);
};

// Notice that index 2 is skipped, since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
9.

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
1

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

Phương thức

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
1 đọc thuộc tính
const arraySparse = [1, 3, /* empty */, 7];
let numCallbackRuns = 0;

arraySparse.forEach((element) => {
  console.log({ element });
  numCallbackRuns++;
});

console.log({ numCallbackRuns });

// { element: 1 }
// { element: 3 }
// { element: 7 }
// { numCallbackRuns: 3 }
7 của
function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}
9 và sau đó truy cập vào từng chỉ mục số nguyên.

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}
2

Thông số kỹ thuật

Sự chỉ rõ
Thông số kỹ thuật ngôn ngữ Ecmascript # sec-array.prototype.foreach
# sec-array.prototype.foreach

Tính tương thích của trình duyệt web

Bảng BCD chỉ tải trong trình duyệt

Xem thêm

Làm thế nào để tôi có được chỉ số hiện tại trong foreach?

Làm thế nào để có được chỉ số của lần lặp hiện tại trong một vòng lặp foreach ...
sử dụng hệ thống ;.
Sử dụng hệ thống.Bộ sưu tập.Chung;.
Lớp học công khai Chỉ mục ..
công khai tĩnh chính ().
số var = new List () {1, 2, 3, 4, 8, 10} ;.
int index = 0 ;.

Foreach có chỉ số không?

Vòng lặp Foreach của C#giúp dễ dàng xử lý một bộ sưu tập: không có biến chỉ mục, điều kiện hoặc mã để cập nhật biến vòng lặp.Thay vào đó, biến vòng lặp được tự động đặt thành giá trị của mỗi phần tử.Điều đó cũng có nghĩa là không có biến chỉ mục với foreach.there's no index variable, condition, or code to update the loop variable. Instead the loop variable is automatically set to the value of each element. That also means that there's no index variable with foreach .

Làm thế nào để bạn có được chỉ mục của một phần tử trong danh sách trong JS?

Phương thức indexof () trả về chỉ mục đầu tiên mà tại đó một phần tử nhất định có thể được tìm thấy trong mảng hoặc -1 nếu nó không có mặt. returns the first index at which a given element can be found in the array, or -1 if it is not present.

Làm thế nào để bạn tìm thấy chỉ số của một vòng lặp?

Sử dụng phương thức Enumerate () để truy cập chỉ số liệt kê () chủ yếu được sử dụng trong các vòng lặp trong đó nó được sử dụng để lấy chỉ mục cùng với phần tử tương ứng trên phạm vi đã cho. to access index enumerate() is mostly used in for loops where it is used to get the index along with the corresponding element over the given range.