JavaScript:函数

0 函数定义

使用关键字 function 定义函数

function 函数名( 形参列表 ){
    // 函数体
    return 返回值;
}

函数声明后不会立即执行,会在我们需要的时候调用到。

注意:

  形参:一定不要带数据类型

  分号是用来分隔可执行JavaScript语句。 由于函数声明不是一个可执行语句,所以不以分号 结束。

1 无返回值

function qiuhe(a, b) {
    var he = a + b;
    console.log("两数之和:" + he);
}

qiuhe(3,4);

2 有返回值

function qiuhe(a, b) {
    var he = a + b;
    return "两数之和:" + he;
}

var s = qiuhe(3,4);
console.log( s );

3 参数对象    

在函数内部,调用参数列表的属性

function func(a,b,c){
    console.log( arguments.length ); // 获得参数的个数
    console.log( arguments[1] ); // 获得下标为1的参数
}

4 构造函数

函数同样可以通过内置的 JavaScript 函数构造器(Function())定义

var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
console.log(x);

注: 上述函数以分号结尾,因为它是一个执行语句。

5 匿名函数

没有名称的函数

var fn = function(a, b) {// 没有名字的函数,应该用一个变量来接收
    return a * 10 + b;
};

console.log( fn(3, 4) );

6 全局函数

isNaN:检查其参数是否是非数字值

console.log( isNaN( 123 ) ); // 数字,false
console.log( isNaN( "hello" ) ); // 非数字,true
console.log( isNaN( 4-1 ) ); // 数字,false
console.log( isNaN( 123 ) ); // 数字,false
console.log( isNaN( -10 ) ); // 数字,false
console.log( isNaN( "123" ) ); // 数字,false
console.log( isNaN( "1a23" ) ); // 非数字,true

eval:用来转换字符串中的运算

var str = "1+3";
console.log( str ); // 1+3 , +会认定为一种字符符号而已,没有加法的作用
console.log( eval( str ) ); // 让字符串中的运算符号生效

encodeURI 与 decodeURI

var name = "拉勾网";
console.log( "转码前:" + name );

name = encodeURI(name);
console.log( "转码后:" + name );

name = decodeURI(name);
console.log( "解码后:" + name );
原文地址:https://www.cnblogs.com/JasperZhao/p/15134129.html