ps: // 之后是结果输出
函数传参情况下,少于3个参数,一般我们使用这样方式:
function test(one, two){
console.log(one, two);
}
test(1, 2) // 1, 2
此种方式有个缺点是,参数必须按照顺序排序传递,比如不能越过one传递two,否则就是undefined
test(2) // 2, undefined
当很多个参数需要传递时,此种方式就是灾难,需要极其小心传递,才不至于掉坑里,使用object对象类型传递,使用解构使用参数,将很好解决这种方式
function test({one, two}){
console.log(two);
}
test({one:1, two:2}) // 2
解构参数使用时,如果没有传递或 'undefined' or 'null',将会报错
test()
// Uncaught TypeError: Cannot destructure property `one` of 'undefined' or 'null'
使用参数解构和默认参数可以很好解决这个问题
function test({one} = {}){
console.log(one);
}
test() // undefined
传参使用object对象方式,需要明确传递object的key值,具体使用根据场景决定。
知道新一种的参数传递方式,增加我们可供选择的权力,这不就是自由么,哈哈!
祝愿您在coding路上,如痴如醉!