首页 > 解决方案 > 数组如何通过读取函数中的未定义参数来识别从自身中提取的内容?

问题描述

我刚刚在 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

标签: javascript

解决方案


forEach在一个数组上工作,并接受一个接受三个参数的回调函数:第一个是 current item,第二个是index当前项的,第三个是对它应用到的数组的引用。

在此示例中,forEach正在迭代fruitsmyFunction作为回调应用。


推荐阅读