首先我们写一个简单的预订功能;
'use strict';
const bookings = [];const createBooking = function (flightNum, numPassengers, price) {const booking = {flightNum,numPassengers,price,};console.log(booking);bookings.push(booking);
};createBooking('LH123');
● 因为我们没有给后面两个参数传值,所有会显示undefined,当然我们可以给参数设置一个初始值;
'use strict';
const bookings = [];const createBooking = function (flightNum, numPassengers, price) {numPassengers = numPassengers || 1;price = price || 199;const booking = {flightNum,numPassengers,price,};console.log(booking);bookings.push(booking);
};createBooking('LH123');
● 这种给参数默认值的方法是ES5提供的,但是这种太过于繁重和丑陋,在ES6中,我们可以直接使用这种方式
'use strict';
const bookings = [];const createBooking = function (flightNum, numPassengers = 1, price = 199) {const booking = {flightNum,numPassengers,price,};console.log(booking);bookings.push(booking);
};createBooking('LH123');
● 当然,我们给函数传参的话,当然不会再是默认值了
'use strict';
const bookings = [];const createBooking = function (flightNum, numPassengers = 1, price = 199) {const booking = {flightNum,numPassengers,price,};console.log(booking);bookings.push(booking);
};createBooking('LH123');
createBooking('LH123', 3, 600);
● 除此之外,默认的参数也可以随其他的参数而变动,如果价格按照人数来
确定
'use strict';
const bookings = [];const createBooking = function (flightNum,numPassengers = 1,price = 199 * numPassengers
) {const booking = {flightNum,numPassengers,price,};console.log(booking);bookings.push(booking);
};createBooking('LH123');
createBooking('LH123', 3);
createBooking('LH123', 5);
● 如果我想跳过人数,给价格赋值,可以这样
'use strict';
const bookings = [];const createBooking = function (flightNum,numPassengers = 1,price = 199 * numPassengers
) {const booking = {flightNum,numPassengers,price,};console.log(booking);bookings.push(booking);
};createBooking('LH123');
createBooking('LH123', 3);
createBooking('LH123', 5);createBooking('LH123', undefined, 1000);