3个有用的JavaScript技巧

1.数组去重

使用ES6全新的数据结构即可简单实现。

let j = [...new Set([1, 2, 3, 3])]
输出: [1, 2, 3]

2.数组和布尔值

当数组需要快速过滤掉一些为false的值(0,undefined,false等)时,一般是这样写:

myArray.map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(item => item);

可以使用Boolean更简洁地实现:

myArray.map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(Boolean);
//例如:

console.log([1,0,null].filter(Boolean));
//输出:[1]

3.合并对象

合并多个对象这个使用展开运算符(...)即可简单实现。

const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };

const summary = {...person, ...tools, ...attributes};
/*
Object {
  "computer": "Mac",
  "editor": "Atom",
  "eyes": "Blue",
  "gender": "Male",
  "hair": "Brown",
  "handsomeness": "Extreme",
  "name": "David Walsh",
}
*/

猜你喜欢

转载自www.cnblogs.com/jiazhi88/p/12362691.html