gpt4 book ai didi

JavaScript 和编程初学者 - 传递函数解释

转载 作者:行者123 更新时间:2023-11-28 07:11:26 25 4
gpt4 key购买 nike

JS初学者,从书上学习,传递函数示例对我来说不清楚。这是代码:

function toCentigrade(degFahren) {
var degCent = 5 / 9 * (degFahren - 32);
document.write(degFahren + " Fahrenheit is " +
degCent + " Celsius.<br/>");
}

function toFahrenheit(degCent) {
var degFahren = 9 / 5 * degCent + 32;
document.write(degCent + " Celsius is " +
degFahren + " Fahrenheit.<br/>");
}

function convert(converter, temperature) {
converter(temperature);
}
convert(toFahrenheit, 23);
convert(toCentigrade, 75);
<!DOCTYPE html>
<html lang="en">

<head>
<title>Chapter 4, Example 2</title>
</head>

<body>
</body>

</html>

我不明白函数转换的部分。这是书上的解释:

Admittedly, you could use these functions as is without any problem, but that wouldn’t result in a very interesting example. Instead, the third function, convert(), will be used to execute toCentigrade() and toFahrenheit():

function convert(converter, temperature) {
return converter(temperature);
}

This function takes the first parameter, converter, and uses it as a function. The second parameter, temperature, is then passed to converter() to perform the conversion and write the results to the document. The final two lines of code use convert() and pass it the appropriate converter function and temperature value:

convert(toFahrenheit, 23);
convert(toCentigrade, 75);

Although this is certainly a more complex solution to a relatively simple problem, it demonstrates the fact that functions are values in JavaScript. We can assign them to variables and pass them to other functions.

我不明白的可能是这个例子的本质 - 为什么参数是(converter, temp),我们如何将温度参数分配给converter (现在是函数内的函数)当未定义 温度 时 - 它只是一个词(对我来说),在 convert 函数之后如何用于转换 (toFahrenheit, 23 和 toCentigrade, 75):例如,函数 toFahrenheit 知道它应该查找 convert 函数用于将转换结果写入网页所需的数字,如何实现?我的意思是,我们到底如何连接此示例中的所有三个函数,从而将结果打印到网页上?基本上,我对所有这部分都迷失了:

function convert(converter, temperature) {
converter(temperature);
}
convert(toFahrenheit, 23);
convert(toCentigrade, 75);

最佳答案

convert(toFahrenheit, 23);

将 toFahrenheit 函数作为参数传递给转换函数。因此:

function convert(converter, temperature) {
converter(temperature);
}

上面的参数转换器只是对 toFahrenheit 函数的引用。因此,在本例中,代码:

converter(temperature);

等同于:

toFahrenheit(temperature);

我认为您的书的作者只是想向您展示如果需要的话可以将函数作为参数传递。

关于JavaScript 和编程初学者 - 传递函数解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31267069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com