究竟什么是功能参数? [英] What exactly are function parameters?

查看:96
本文介绍了究竟什么是功能参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根本不理解他们。我所知道的最多的是:



I don't really understand them at all. The most I know is this:

function Test(a, b) {
alert(a + b);
}

Test("Hello ", "World!");
//Alerts "Hello World!"



我理解这个函数中的a和b是什么。但在下一个例子中,我不知道a和b是什么。看看:




I understand what a and b is in this function. But in the next example, I have no idea what a and b are. Take a look:

function Sort() {
var arr = [31, 1, 71, 500];
arr.sort(function(a, b) {return a - b});
alert(arr);
}
//Alerts "1,31,71,500". Without the parameters, it sorts as "1,31,500,71".

但我仍然不知道a和b是什么,或者他们是如何设法正确排序的。



我尝试过:



没什么。 Sololearn上没有人理解我的问题,所以现在我在这里。 xD

But I still don't know what a and b are, or how they managed to sort it correctly.

What I have tried:

Nothing. Nobody on Sololearn understood my question, so now i'm here. xD

推荐答案

javascript数组对象的排序函数取1参数或无参数。



会发生什么如果没有参数?按字母顺序排序。为了告诉javascript你要如何排序你需要将一个函数作为参数传递给sort函数。参数函数有两个参数,零或正非零或负非零(哈哈)



sort function of javascript array object take 1 parameter or no parameter.

what would happen if no paramerter? it sort alphabetically. in order to tell javascript howyou want to sort you need to pass a function as parameter to sort function. The parameter function takes two arguments and either zero or positive non zero or negative non zero (haha)

funtion comp(a, b) {
 return a-b; // 0 means equal, negative means a is small.
}
arr.sort(comp);



在您的示例中,您的函数是匿名的。这个功能不可重复使用,执行后会丢失





我会给你一个例子,这样你就可以理解匿名功能了。



假设我们有一个产生hello world的功能。但是函数本身不会呈现结果。相反,函数使用提供的机制来表示数据。


in your example your function is anonymous. this fuction is not reusable and will be lost after execution


I will give you an example, so that you can understand anonymous function.

Let's say we have a function that produce "hello world". But the function itself do not render the result. Instead function uses provided mechanism to represent data.

function HelloWorld(func) {
 // we will use this func to render the result
 var result="Hello World";
 func(result); // we are using func as a function 
}

// now let's use HelloWorld function to utilize data; 
function DisplayToDiv(res) {
 document.getElementById("divid").innerHtml = res;
} 

// call the function
HelloWorld(DisplayToDiv); 

// let's write the next command to output as console result 

HelloWorld(function /*name is not required*/(res){
 console.log(res);
});

// another example
HelloWorld(alert); // does alert look familiar to you?





希望这有帮助





哦!顺便说一句,你传递的这个函数叫做回调函数


这篇关于究竟什么是功能参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆