javascript - 数组如何通过读取函数中的未定义参数来识别从自身中提取的内容?
问题描述
我刚刚在 W3school 中阅读了一个示例。这个函数似乎知道这些参数(项目、索引)在数组中代表什么。这是为什么?
<!DOCTYPE html>
<html>
<body>
<p>List all array items, with keys and values:</p>
<p id="demo"></p>
<script>
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
</script>
</body>
</html>
结果
List all array items, with keys and values:
0:apple
1:orange
2:cherry
解决方案
forEach
在一个数组上工作,并接受一个接受三个参数的回调函数:第一个是 current item
,第二个是index
当前项的,第三个是对它应用到的数组的引用。
在此示例中,forEach
正在迭代fruits
并myFunction
作为回调应用。
推荐阅读
- r - 有什么方法可以清除 R 中我的数据集列中的引号“”
- python - python: update (source newer than destination or destination missing) copy files
- reactjs - react js中的嵌套路由不能正常工作?
- javascript - 将对象传递给事件函数
- vb.net - 将内部和外部边界设置在一条线上
- arrays - 您可以使用嵌套了 SUBSTITUTE/LEN/RIGHT 函数的 ArrayFormula 复制列中的公式吗?
- javascript - 如何在 js 脚本中的窗口中删除事件侦听器或不在 chrome devtools 中的 puppeteer
- reactjs - react-router-dom > NavLink > 多个activeClassName?
- azure-virtual-machine - 如何在 Azure 虚拟机中为在 Hyper-V 下运行的群集创建共享磁盘?
- encryption - 如何将openssl加密和解密转换为php