绪论
写JS方法会碰到参数不固定的时候,把每个参数都赋值又感觉麻烦,就想有没有办法设置个默认值呢?果然有解决方法。在此记录一下。
正文
<!DOCTYPE html><div lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>index</title><script src="js/jquery-2.2.4.min.js"></script><style></style></head><body></body><script>$(document).ready(function () {Node1();Node1(10);Node1(10, null, null);Node2();Node2(10);Node2(10, null, null);// 参数必须为{},否则报错Node3({});Node3({data:10});Node3({data:10, left:null, right:null});// 可以没有参数Node4();Node4({data:10});Node4({data:10, left:null, right:null});});function Node1(data, left, right) {console.log('Node1方法:data:' + data + ', left:' + left + ', right:' + right);}function Node2(data = 21, left = 22, right = 23) {console.log('Node2方法:data:' + data + ', left:' + left + ', right:' + right);}function Node3({data = 31, left = 32, right = 33}) {console.log('Node3方法:data:' + data + ', left:' + left + ', right:' + right);}function Node4({data = 41, left = 42, right = 43} = {}) {console.log('Node4方法:data:' + data + ', left:' + left + ', right:' + right);}</script></div>
结果
(若有什么错误,请留言指正,3Q)