标签:输入 tag 可变参数 apply() 对象 script undefined function 解构赋值
//javascript的函数 //代码1: ‘use strict‘ function foo(x) { console.log(‘x= ‘ + x); for(var i = 0; i < arguments.length; i ++) { console.log(‘arguments[‘ + i + ‘]=‘ + arguments[i]); } }; foo(1,2,3,4,5); //代码1解说: //1.方法使用的参数可多于或少于指定数目 //2.‘arguments‘关键字类似数组,用来显示输入的参数 //代码2: ‘use strict‘ function func1(a, b, c) { if (arguments.length === 2) { c = b; b = null; } console.log(a + c); }; func1(1,2); //代码2解说: //1.‘arguments‘关键字用于判断参数传入的个数,上面的//代码将参数b变为可变参数 //代码3: ‘use strict‘ function func1(a, b, ...rest) { console.log(a); console.log(b); console.log(rest); }; func1(1,2,3,4,5); //1 //2 //[3,4,5] func1(1); //1 //undefined //[] //代码3解说: //1.ES6标准引入了‘rest‘关键字,用来获得剩余的全部参数 //代码4: ‘use strict‘ function sum(...rest) { var sum = 0; for (var i = 0; i < rest.length; i ++) { sum += rest[i]; } return sum; }; var result = sum(1,2,3,4,5); console.log(result); //15 //代码4解说: //1.上面的方法sum(...rest)作用是对输入的参数进行求和 //代码5: ‘use strict‘ function fun1() { var job = ‘cook‘, desciption = ‘ cook delicious food‘; console.log(job + desciption); }; fun1(); //代码5解说: //1.由于变量提升的存在,js函数最好在起始位置声明所有变量 //代码6: var a = 1, b = 2; [a, b] = [b, a]; console.log(a); console.log(b); //应用举例1:交换变量a和b的值 var {hostname:domain, pathname:path} = location; //应用举例2:获取当前页面的域名和路径 //代码6解说: //1.解构赋值的应用 //代码7: function getAge() { var year = new Date().getFullYear(); return year - this.birthYear; } var li = { name: ‘李‘, birthYear: 1991, age: getAge } var ageLi = li.age(); console.log(ageLi); //27 ageLi = getAge(); console.log(ageLi); //NaN ageLi = getAge.apply(li, []); console.log(ageLi); //27 //代码7解说: //1.使用apply()方法改变this的指向 //代码8: ‘use strict‘ var count = 0; var oldParseInt = parseInt; window.parseInt = function() { count += 1; oldParseInt.apply(null, arguments); } for (var i = 0; i < 5; i ++) { parseInt(‘19‘); } console.log(count); //代码8解说: //1.替换‘window‘对象的函数‘parseInt‘,让它具有计数功能
标签:输入 tag 可变参数 apply() 对象 script undefined function 解构赋值
原文地址:https://www.cnblogs.com/mexding/p/8944571.html