~~a
或
a|0
a+.5|0
!0
!!0
''.concat(a, b, c)
- 展平数组(在使用嵌套数组时,这是一项非常有用的技术)
const flattenedArray = [].concat(...array);
let time = +new Date();
if (name === 'XX') {
flag = true;
} else {
flag = false;
}
flag = name === 'XX';
if (name === 'XX') {
age = 20;
} else {
age = 18;
}
age = name === 'XX' ? 20 : 18;
if (arr.length !== 0) {}
if (arr.length) {}
if (arr.length === 0) {}
if (!arr.length) {}
- includes简化同一条件多种结果判断(个人比较喜欢用)
if (a === 1 || a === 2 || a === 3 || a === 4) {}
if ([1, 2, 3, 4].includes(a)) {}
let name = person.name || 'XX'
let name = person && person.name;
let name = person?.name;
function setData({ a, b = 2 }) {
this.a = a;
this.b = b;
}
let obj = {
a: 1,
b: 2
};
let keys = Object.keys(obj);
let obj = {
a: 1,
b: 2
};
let keys = Object.values(obj);
arr.forEach((item, index) => {
item.name = 'XX';
});
let newArr = arr.filter((item, index) => index > 2);
let newArr = arr.map(item => {
return Object.assign({}, item, { name: 'XX' });
})
let flag = arr.some((item, index) => item.name === 'XX');
- every()数组中的每项是否都满足条件,返回布尔值
let flag = arr.every((item, index) => !!item.name);
- reduce()对数组中的每一项执行提供的reducer函数,最后返回汇总结果
let sum = [1, 2, 3, 4, 5].reduce((acc, current) => {
return acc + current;
}, 0);
if (color === 'red') {
switchRedColor();
} else if (color === 'grey') {
switchGreyColor();
} else if (color === 'yello') {
switchYellowColor();
} else if(color === 'white') {
switchWhiteColor();
}
switch(color) {
case 'red':
switchRedColor();
break;
case 'grey':
switchGreyColor();
break;
case 'yello':
switchYellowColor();
break;
case 'white':
switchWhiteColor();
break;
}
const colors = {
'red': switchRedColor,
'grey': switchGreyColor,
'yellow': switchYellowColor,
'white': switchWhiteColor
};
for (color in colors) {
colors[color]();
}
const colors = new Map([
['red', switchRedColor],
['grey', switchGreyColor],
['yellow', switchYellowColor],
['white', switchWhiteColor]
]);
for (color in colors) {
colors[color]();
}
let obj = {
name: 'kingX'
};
if (obj[name]) {}
obj.hasOwnProperty('name');
'name' in obj
obj.hasOwnProperty('valueOf')
'valueOf' in obj
arr.indexOf(text) > -1
arr.includes(text)
~~!arr.indexOf(text)
<ul>
<li></li>
<li onclick="getIndex()"></li>
</ul>
function getIndex(ev) {
let ev = ev || event;
let target = ev.target;
return [].indexOf.call(document.querySelectorAll('li'). target);
}