2021铁人赛
没说什麽,用工具人运作来讲了一个故事
方函式:说起来(电话响)... 喂?有字串姐的东西?你收了吧?好喔,先这样。
我:...你经营物流?
方函式:我小弟参数打来的,他负责帮我收取JS跟姐妹们的东西
function testParameters([a, b, c], { name, intersted }, cool) {
console.log(a + b + c, "我是阵列传入内容");
console.log(name + intersted, "我是物件传入内容");
console.log(cool(), "我是函式传入内容");
return a + b + c;
}
testParameters(
[1, 2, 3],
{ name: "Andy", intersted: " watching movie" },
function cool(i) {
return 1;
}
);
//也可解构参数,有更灵活的运用
//把name里面的a,b,c拆解出来
function destructingInput({name:[a,b,c]}){
console.log(a+b+c);
return a+b+c;
}
let x = {name:[1,2,3]};
destructingInput(x);
在上面的案例,我除了基本示范将物件、阵列、函式传入函式外,也有试着做简易的参数解构赋值。
--
undefined
function beforeEs6(a,b){
return a + b; // 1 + undefined
}
//少输入一个引数值就得到意外的结果
console.log(beforeEs6(1));//get NaN
//解决方式:函式内加入条件判断
function beforeEs6(a,b){
if(b === undefined) b =1
return a + b;
}
像这样少输入引数引发的各种问题,在ES6的预设参数以及不定参数出现後,提供你更多的变通方法。
...restParameters
:1. 不定参数本身是一个阵列(所有引数内容依序装入阵列)
所以,各类的Array.properties
它都可以使用
下面先证明一下它确实是阵列:
//Number + restParameter
function trys(first,...afterSeconds){
//透过Array.isArray来判断,会回传 true / false
console.log(Array.isArray(afterSeconds));
}
trys()
function oneRestParameters(...firstRest,test){
console.log(firstRest + test,"我是只有一个不定参数的情境");
return firstRest + test;
}
oneRestParameters(1,2,3)
function addTwoRestParameters(...firstRest,test,...secondRest){
console.log(firstRest + test + secondRest,,"我是有两个不定参数的情境");
}
addTwoRestParameters(1,2,3,4)
所以上述两个执行都会报错,因为上面有提过不定参数只有一个且要放在最後。
3. 就算没有输入引数值,不定参数本身也会建立一个空阵列
function trys(first,...afterSeconds){
console.log(first);
console.log(afterSeconds);
return first + afterSeconds;
}
console.log(trys(1));
可预先为参数赋值,各型别都可以:
function befores(a,b=1){
return a +b;
}
//就算少输入也不会得到意外的结果
befores(1); // get 2
function befores([a,b,c]=[]){
return a + b + c;
}
//没输入引数也不会报错
console.log(befores());
console.log(befores([1,2,3]));
falsy
值时 falsy值有哪些参考
function inputFalsyValue(value = 1){
return value;
}
//falsy值
console.log(inputFalsyValue("")); //""
console.log(inputFalsyValue(null)); //null
console.log(inputFalsyValue(undefined)); // 1 ?!
console.log(inputFalsyValue(0)); //0
为何null
能成功传入,但undefined
却回传1
呢?
目前所知JS内部机制在检测函式传入值时,只要是undefined
,就会启动预设参数的机制。
欲知更多相关:Handling the distinction between undefined- and null-parameters in JavaScript
-- to be continued --
那今天就到这边搂!今天分享喜欢的歌是:
Hedwig and The Angry Inch - Midnight Radio
https://www.youtube.com/watch?v=ZynpwOfEOSM
每天的休息,是为了後面的追求,明天见。
不知不觉已经到了这个挑战的终点,现在回头看,应该有比刚开始的自己更进步了吧! 想当初参加这比赛时,因...
今天要来讲介面型别的使用范例。 通常我们会使用介面来定义函式型别,程序码如下, interface ...
介绍JSX JSX 是一种在 JavaScript 里面的标签语法,让我们可以在写逻辑时使用 HTM...
一开始加入面试会议时,心里不知道要问些什麽,但与同事们不断讨论过後,才慢慢摸索出要如何开口提问。与其...
All life is an experiment. The more experiments y...