4个有用的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",
}
*/

4.提取 JSON 数据

 解构赋值对提取 JSON 对象中的数据,尤其有用。

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]

 

posted @ 2020-02-26 11:06  机智的蛋炒饭  阅读(147)  评论(0编辑  收藏  举报