new javascript features
Default params
function rollDie(numSides = 6) {
return Math.floor(Math.random() *numSides) +1
}
//default is set to 6
function greet (person, msg ="hey there"){
}
//default greeting: hey there
spread 扩展运算符
spread syntax allows an iterable such as an array to be expanded in places where zero or more arguments ( for function calls) or elements(for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals)are expected 它可以在函数调用/数组构造时,将数组表达式或者string在语法层面展开;还可以在构造字面量对象时将对象表达式按照key-value的方式展开 说白了就是把衣服脱了,不管是大括号([])、花括号({}),统统不在话下,全部脱掉脱掉!
它的用处很广泛,我们随处都可以看到,下面是几个常见的例子
复制用它 合并用它 字符转数组用它 函数传参用它
//数组的合并 var arr1 = ['hello'] var arr2 =['chuichui'] var mergeArr = [...arr1,...arr2] mergeArr // ['hello','chuichui'] // 对象分合并 var obj1 = {name:'chuichui'} var obj2 = {height:176} var mergeObj = {...obj1,...obj2} mergeObj // {name: "chuichui", height: 176}
Math.max(12,2,34,343,222)
const nums = [12,2,34,343,222]
Math.max(nums)//NaN
Math.max(...nums)//343
expands an itetable(array, string,etc.)into a list of arguments
const cats = ['blue', 'scout']
const dogs =['rusty', 'wyatt']
const allPets = [...cats,...dogs]//['blue', 'scout', 'rusty', 'wyatt']
[..."hello"]
//["h","e","l","l","o"]
copies properties from one object into another object literal
const dataFromForm = {
email: 'ekefjk@email.com',
password:'tovfi',
}
const newUser = {...dataFromForm, id: 2345, idAdmin: false}
REST 剩余运算符
It looks like spread but it is not. collects all remaining arguments into an actual array
the arguments object
availiable inside every function
it is an array-like object
-has a length property
- does not have array methods like push/pop
contains all the arguments passed to the function
not available inside of arrow functions
function sum(...nums){
console.log(nums)
}
sum(3,4,5)
//[3,4,5]
function raceResults(gold, silver, ...everyoneElse) {
console.log(`gold medal:${gold}`)
console.log(`silver medal:${silver}`)
console.log(`and thanks to others ${everyoneElse}`)
}
raceResults('tammy','toddy','tina','travis')
//gold medal:tammy
//silver medal:toddy
//and thanks to others tina, travis
destructuring arrays
a short clean syntax to unpack:
-values from arrays
- properties from objects into distinct variables
const scores = [98888,78888,33334,99999,10000];
const [gold, silver, bronze, ...everyoneElse] = scores;
everyoneElse//99999,10000
destructuring objects
const runner = {
first : "eliu"
last :"kefr"
country: Us
}
const {first, last} = runner;//no need to write const first = runner.first which is quite long
first;//"elie"
last;//"kefr"
const {first:fir}=runner//rename
const {first, last, died ="N/A"}= runner //"N/A" is the default value
destructuring params
function fullName({first, last}){
return `${first} ${ last}`
}
fullName(runner)
//eliu kefr