前端的初学习 -- 第七章 -- JavaScript函数
博客说明
文章内容输出来源:拉勾教育Java就业急训营
声明函数
无返回值
function qiuhe(a, b) {
var he = a + b;
console.log("两数之和:" + he);
}
qiuhe(3,4);
有返回值
function qiuhe(a, b) {
var he = a + b;
return "两数之和:" + he;
}
var s = qiuhe(3,4);
console.log( s );
参数对象
在函数内部,调用参数列表的属性
function func(a,b,c){
console.log( arguments.length ); // 获得参数的个数
console.log( arguments[1] ); // 获得下标为1的参数
}
构造函数
函数同样可以通过内置的 JavaScript 函数构造器(Function())定义
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
console.log(x);
匿名函数
var fn = function(a, b) {// 没有名字的函数,应该用一个变量来接收
return a * 10 + b;
};
console.log(fn(3, 4));
全局函数
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 );
闭包
a = 10; // 全局变量:声明的时候可以不使用var
function test1() {
b = 20; // 全局变量:不使用var声明的变量,就是全局变量
// 局部变量:用var声明,并且在函数的内部。这样的变量叫做局部变量,有效范围只能 在其声明的函数内部
var c = 30;
console.log(c);
}
function test2() {
console.log(c); //c is not defined (c变量没有定义)
}
test1();
test2();
闭包例子:
需求:统计方法执行了多少次
function test1() {
var count = 0; //局部变量
function jia() {
return count += 1;
}
return jia;
}
var fn = test1(); // fn => function jia(){return count+=1; }
fn();
fn();
console.log(fn()); // 每次调用方法,首先就是将变量还原为0