这么骚的JavaScript代码,你确定不来瞅瞅? (第1期)
1、动态属性名称
let name = 'flav';
let item = {
sex: 0,
[name]: 'Ama'
}
console.log(item);
// {sex: 0, flav: "Ama"}
2、解构赋值
let a = 1, b = 2;
[a, b] = [b, a];
// a: 2
// b: 1
3、扩展操作符
let a = [...'Hello World'];
// ["H","e","l","l","0","W","o","r","l","d"]
4、左移运算符 <<
1 << 2
// 4,即2的2次方
1 << 10
// 1024,即2的10次方
5、使用 &
判断奇偶性
偶数 & 1 = 0
奇数 & 1 = 1
7 & 1
// 1
8 & 1
// 0
6、!!
将数字转为布尔值
!!7
// true
!!0
// false
!!-1
// true
!!0.71
// true
7、n & (n - 1)
,如果为 0,说明 n 是 2 的整数幂
let n = 24;
n & (n - 1);
// 16
n = 64;
n & (n - 1);
// 0
8、逻辑运算符和赋值表达式
a ||= b;
// ==
a = a || (a = b);
a &&= b;
// ==
a = a && (a = b);
a ??= b;
// ==
a = a ?? (a = b);
9、Promise.finally()
function consoleFun(){
return new Promise((resolve,reject) => {
let toggle = 10;
if(toggle > 5){
console.log('大于');
resolve('大于');
}else {
console.log('小于');
reject('小于');
}
})
}
// 调用
consoleFun.then(() => {
console.log('SUCCESS');
}).catch(() => {
console.log('ERROR');
}).finally(() => {
console.log('FINALLY');
// This function is always excuted!
})
10、Rest/Spread属性
const values = [1, 2, 3, 5, 6];
console.log( Math.max(...values) );
// 6
11、控制合并符
let user = {
u1: 0,
u2: false,
u3: null,
u4: undefined
u5: '',
}
let u2 = user.u2 ?? '用户2'
// false
let u3 = user.u3 ?? '用户3'
// 用户3
let u4 = user.u4 ?? '用户4'
// 用户4
let u5 = user.u5 ?? '用户5'
// ''
12、使用reduce实现数组filter()方法
const selfFilter = function (fn, context) {
return this.reduce((pre,cur,index) => {
return fn.call(context,cur,index,this) ? [...pre,cur] : [...pre];
}, [])
}
13、循环实现数组的some()方法
const selfSome = function (fn, context) {
let arr = Array.prototype.slice.call(this);
if (!arr.length) return false;
for (let i = 0; i < arr.length; i++){
if(!arr.hasOwnProperty(i)) continue;
let res= fn.call(context, arr[i], i, this);
if (res) return true;
}
return false;
}
14、判断对象的数据类型
const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target);
const isArray = isType('Array');
isArray([]);
// true
15、逗号运算符
let x = 1;
x = (x++, x);
console.log(x);
// 2
x = (2,3);
console.log(x);
// 3
16、获取数组中唯一值
const arr = [1,5,1,5,4,56,4,8,4,4,85,4,5];
const soleValue = Array.from(new Set(arr));
console.log(soleValue);
// 1, 5, 4, 56, 8, 85
17、函数柯里化
function add(a, b) {
return a + b;
}
let add1 = add.curry(1);
console.log(add1(5));
// 6
console.log(add1(2));
// 3
18、防止篡改对象
let person = {
name: 'yin'
};
Object.seal(person);
delete person.name
// 不能删除
person.age = 18;
console.log(person.age);
// undefined
19、一次性函数
let sca = function() {
console.log('msg')
sca = function() {
console.log('foo')
}
}
sca()
// msg
sca()
// foo
sca()
// foo
20、立即执行函数
(function init() {
// ...
})()
- 最后给大家带来一些自己常用的一些实用工具和学习资料:
- 【开源的代码搜索工具】https://gitee.com/SourceCoding/kooder.git
- 【红包雨转盘】https://gitee.com/SourceCoding/sol-weapp.git
- 【打砖块游戏(H5)】https://gitee.com/SourceCoding/make-bricks.git