在 JavaScript 中使用 foreach() 迴圈時,可以更改陣列的值嗎?


陣列是一種可以儲存多個相同資料型別元素的資料型別。例如,如果陣列宣告為整數型別,則它儲存一個或多個整數型別元素。

在迴圈中,可以使用任何數學運算來運算元組元素。例如,如果陣列元素是數字,則可以將這些數字乘以一個固定數字,也可以進行加法或減法運算。可以使用使用者自定義程式更改陣列元素,每個元素的結果取決於此函式的功能。

forEach 方法

forEach() 迴圈將使用者定義的函式作為引數。此函式具有三個引數,包括可選引數。第一個引數是要在 forEach 迴圈中更新的陣列值。

第二個引數是可選引數,即當前元素的索引;第三個引數也是可選引數,即在 forEach 迴圈中迭代時要進行更新的陣列。

語法

這是 JavaScript 中 foreach() 迴圈的語法:

Object.forEach(function(value,index,array)

其中:

  • function(value,index,array) − 這是 forEach 迴圈的引數函式。這是為每個元素呼叫的使用者定義函式。

  • value − 這是給定陣列或迭代物件的當前值。

  • index − 這是給定陣列或迭代物件中當前值的索引。

  • array − 這是在 forEach 迴圈中進行更改的陣列。

示例 1

在下面的示例中,我們嘗試使用 forEach() 迴圈更新陣列元素:

let employee = ['Abdul', 'Yadav', 'Badavath','Jason']; console.log("The given array with its type is:",employee,typeof(employee)); employee.forEach(myFun); function myFun(item, index, a) { a[index] = 'Intern-Software Engineer ' + item; } console.log("The updated array while in foreach loop with the type is:"); console.log(employee);

示例 2

以下是另一個示例,我們在這裡將陣列元素(字串值)的大小寫更改為句子大小寫:

let employee = ['abdul', 'yadav', 'badavath','jason']; console.log("The given array with its type is:",employee,typeof(employee)); employee.forEach(myFun); function myFun(item, index, a) { a[index] = item[0].toUpperCase() + item.substring(1) } console.log("The updated array while in foreach loop with is:", employee);

示例 3

在這個示例中,我們用元素的平方值替換陣列的元素。

let arr = [1, 2, 3, 4]; arr.forEach((val, index) => arr[index] = val * val); console.log(arr);

更新於:2022年9月2日

6K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.