目录
1,位运算,双位操作符
Math.floor(4.9) === 4 //true
/*------------------------------------------------------------------------*/
~~4.9 === 4 //true 运行速度更快哟
2,Object[key]的妙用
表单验证太繁杂?可重用验证函数搞定~
function validate(values) {
if (!values.first) return false;
if (!values.last) return false;
return true;
}
console.log(validate({ first: 'edison', last: 'yuan' }))
/*------------------------------------------------------------------------*/
const schema = {
first: {
required: true
},
last: {
required: true
}
}
const validate = (schema, values) => {
for (field in schema) {
if (schema[field].required) {
if (!values[field]) {
return false;
}
}
}
return true;
}
console.log(validate(schema, { first: 'edison' }))
console.log(validate(schema, { first: 'edison', last: 'yuan' }))
3,Array.find
es6中 find() 实现 for循环 的简写
const pets = [
{ type: 'Dog', name: 'aa' },
{ type: 'Cat', name: 'kk' },
{ type: 'Dog', name: 'mm' }
]
function findDog(name) {
for (let i = 0; i < pets.length; i++) {
if (pets[i].type === 'Dog' && pets[i].name === name) {
return pets[i];
}
}
}
console.log(findDog('mm'))
/*-------------------------------------------------------*/
const pets = [
{ type: 'Dog', name: 'aa' },
{ type: 'Cat', name: 'kk' },
{ type: 'Dog', name: 'mm' }
]
var pet = pets.find(obj => obj.type === 'Dog' && obj.name === 'mm')
console.log(pet)
4,展开运算符 ...z
//joining arrays
const odd = [1, 3, 5]
const nums = [2, 4, 6].concat(odd); //[2, 4, 6, 1, 3, 5]
//cloning arrays
const arr = [1, 2, 3, 4]
const arr2 = arr.slice(); //[1, 2, 3, 4]
/*------------------------------------------------*/
//joining arrays
const odd = [1, 3, 5]
const nums = [2, 4, 6,...odd] //[2, 4, 6, 1, 3, 5]
const odd = [1, 3, 5]
const nums = [2, ...odd, 4, 6] //[2, 1, 3, 5, 4, 6]
//cloning arrays
const arr = [1, 2, 3, 4]
const arr2 = [...arr] //[1, 2, 3, 4]
/*------------------------------------------------*/
//展开运算符和ES6解构符号结合使用
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) //1
console.log(b) //2
console.log(z) //{c: 3, d: 4}
5,模板字符串 ``
使用 反引号 和 ${} 将变量合成一个字符串
const url = 'http://'+host+':'+port+'/'+database;
/*---------------------------------------------------------*/
const url = `http://${host}:${port}/${database}`;
6,默认参数值和强制参数
//默认参数
function numss(a, b, c) {
if (b === undefined) {
b = 2
}
if (c === undefined) {
c = 3
}
return a * b * c;
}
/*---------------------------------------------------*/
//默认参数
const numss = (a, b = 2, c = 3) => (a * b * c);
console.log(numss(3)) //18
/*--------------------------------------------------*/
//强制参数
const mustval = () => {
throw new Error('Missing parameter!');
}
const numss = (a = mustval(), b = 2, c = 3) => (a * b * c);
console.log(numss()) // Uncaught Error: Missing parameter!
7,箭头函数可以隐式返回值
function aa(num) {
return Math.PI * num
}
/*---------------------------------------------------------*/
//使用 () 而不是 {}
const func = num => (Math.PI * num)