在 javascript 中执行 foreach() 时是否可以更改数组的值?

javascriptweb developmentfront end technology更新于 2024/7/29 22:54:00

数组是一种可以存储多个类似数据类型元素的数据类型。例如,数组被声明为整数数据类型,然后它存储一个或多个整数数据类型的元素。

在数组中,元素可以在循环中使用任何数学运算来操作。例如,如果数组元素是数字,那么数字可以乘以一个固定数字,也可以加或减。数组元素的更改可以通过使用用户定义的程序来完成,每个元素的结果取决于此函数的功能。

forEach 方法

forEach() 循环将用户定义的函数作为参数。此函数有三个参数,包括可选参数。第一个参数是要在 forEach 循环中使用时更新的数组的值。

第二个参数是可选参数,即当前元素的索引,第三个参数也是可选参数,即在 forEach 循环中迭代时要更新的数组。

语法

这是 JavaScript 中 foreach() 循环的语法 −

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

其中,

  • function(value,index,array) − 这是 forEach 循环的参数函数。这是为每个元素调用的用户定义函数。

  • value − 这是给定数组或迭代的当前值对象。

  • 索引 − 这是给定数组或迭代对象的当前值的索引。

  • 数组 − 这是在 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);

相关文章