forEach() 是一个遍历数组并对各个元素执行指定操作的 JavaScript 方法。具体用法包括:遍历数组元素:使用回调函数接收每个元素的值。操作数组元素:在回调函数中修改数组元素的值。中断循环:使用 break 语句在满足特定条件时退出循环。

JavaScript 中 forEach() 的用法
什么是 forEach()?
forEach() 是 JavaScript 中的一个内置方法,用于遍历数组中的每个元素。它接受一个回调函数作为参数,该回调函数在数组的每个元素上执行指定的操作。
语法:
<code class="javascript">array.forEach(callback(currentValue, index, array))</code>
参数:
用法:
<code class="javascript">const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number); // 输出:1 2 3 4 5
});</code><code class="javascript">const names = ['John', 'Mary', 'Bob'];
names.forEach((name, index) => {
names[index] = name.toUpperCase(); // 将所有名字转换为大写
});
console.log(names); // 输出:['JOHN', 'MARY', 'BOB']</code><code class="javascript">const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
if (number > 3) {
break; // 退出循环
}
console.log(number); // 输出:1 2 3
});</code>注意事项:
以上就是js中foreach的用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号