2019 年编写现代 JavaScript 代码的5个小技巧

作者:闭包旅人时间:2026-10-22 20:22:30浏览:199

本文总结了2019年编写现代JavaScript代码的5个实用技巧,涵盖利用Array.includes简化条件判断、使用Set进行数组与字符串去重及集合运算、利用Map处理非字符串键的字典数据、通过函数式编程优雅处理数据转换与求和,以及掌握compose函数组合实现复杂逻辑。

引言

以下内容主要源自今年从其他技术文章中学到的知识,在此整理分享。

使用 Array.includes 替代条件判断

1 使用 Array.includes 替代条件判断

在常规开发中,我们通常使用 || 运算符进行多重条件判断。


// condition
function test(fruit) {
 if (fruit == "apple" || fruit == "strawberry") {
  console.log("red");
 }
}

假设有更多水果需要判断的情况。


function test(fruit) {
 const redFruits = ["apple", "strawberry", "cherry", "cranberries"];

 if (redFruits.includes(fruit)) {
  console.log("red");
 }
}

利用 Set 进行去重与集合运算

2 利用 Set 进行去重

ES6 引入了新的数据结构 Set,它类似于数组,但成员值唯一,无重复。Set 本身是一个构造函数,用于生成 Set 实例。

数组去重示例


const arr = [3, 5, 2, 2, 5, 5];
const unique = [...new Set(arr)];
// [3,5,2]

Array.from 方法可将 Set 结构转换为数组,借此可编写专门的去重函数。


function unique(array) {
 return Array.from(new Set(array));
}

unique([1, 1, 2, 3]); // [1, 2, 3]

字符串去重示例


let str = [...new Set("ababbc")].join("");
console.log(str);
// 'abc'

此外,利用 Set 的强大功能,可以轻松实现并集(Union)、交集(Intersect)和差集(Difference)运算。


let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}

// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

使用 Map 处理字典类型数据

3 使用 Map 处理字典类型数据

通常,JavaScript 实现字典数据依赖 Object 对象,但对象的键只能是字符串,这给编程带来诸多不便。ES6 提供了 Map 数据结构,它类似于 Object,也是键值对的集合,但其“键”的范围不限于字符串,可以是数值、布尔值、数组、对象等各种类型的值。


const resultMap = new Map()
 .set(-1, {text:'小于',color:'yellow')
 .set(0, {text:'等于',color:'black')
 .set(1, {text:'大于',color:'green')
 .set(null,{text:'没有物品',color:'red'})

let state = resultMap.get(null)
// {text:'没有物品',color:'red'}

Map 的遍历顺序与插入顺序一致。


const map = new Map([["F", "no"], ["T", "yes"]]);

for (let key of map.keys) {
 console.log(key);
}
// "F"
// "T"

for (let value of map.value()) {
 console.log(value);
}
// "no"
// "yes"

采用函数式方式处理数据

4 采用函数式方式处理数据

理解上,函数式编程主张函数必须接受至少一个参数并返回一个值。因此,所有数据操作均可通过函数式方式处理。

假设需求为:先修改数组 foo 中对象的结构,再筛选出符合条件的对象,并将结果放入新数组 result 中。


let foo = [
 {
  name: "Stark",
  age: 21
 },
 {
  name: "Jarvis",
  age: 20
 },
 {
  name: "Pepper",
  age: 16
 }
];

//我们希望得到结构稍微不同,age大于16的对象:
let result = [
 {
  person: {
   name: "Stark",
   age: 21
  },
  friends: []
 },
 {
  person: {
   name: "Jarvis",
   age: 20
  },
  friends: []
 }
];

从直觉出发,很容易写出如下代码。


let result = [];

//有时甚至是普通的for循环
foo.forEach(function(person){
  if(person.age > 16){
    let newItem = {
      person: person,
      friends: [];
    };
    result.push(newItem);
  }
})

使用函数式写法,代码可以更加优雅。


let result = foo
 .filter(person => person.age > 16)
 .map(person => ({
  person: person,
  friends: []
 }));

数组求和示例


let foo = [1, 2, 3, 4, 5];

//不优雅
function sum(arr) {
 let x = 0;
 for (let i = 0; i < arr.length; i++) {
  x += arr[i];
 }
 return x;
}
sum(foo); // => 15

//优雅
foo.reduce((a, b) => a + b); // => 15

使用 compose 进行函数组合

5 使用 compose 进行函数组合

以下代码称为组合 compose。


const compose = function(f, g) {
 return function(x) {
  return f(g(x));
 };
};

随着函数式编程的流行,现在 JavaScript 代码中随处可见箭头函数链式调用。

ES6 版本的 compose 实现。


const compose = (f, g) => x => f(g(x));

在 compose 定义中,g 将先于 f 执行,从而形成从右到左的数据流。这种写法的可读性远高于嵌套大量函数调用。

我们可以选择一些函数进行结合,生成一个新函数。

reverse 用于反转列表,head 用于获取列表中的第一个元素。


const head = arr => arr[0];
const reverse = arr => [].concat(arr).reverse();

const last = compose(head, reverse);
last(["jumpkick", "roundhouse", "uppercut"]);
// "uppercut"

然而,上述 compose 实现不够完善,仅能处理两个函数参数。可借鉴 redux 源码中完备的 compose 函数。


function compose(...funcs){
 if (funcs.length === 0){
   return arg => arg
 }

 if (funcs.length === 1 ){
   return funcs[0]
 }

 return funcs.reduce((a,b)=>(...args) => a(b(...args)))
}

有了该函数,我们可以随意组合无数个函数。现增加需求:组合出一个 lastAndUpper 函数,内容为先 reverse 反转列表,head 取列表中的第一个元素,最后 toUpperCase 转为大写。


const head = arr => arr[0];
const reverse = arr => [].concat(arr).reverse();
const toUpperCase = str => str.toUpperCase();

const last = compose(head, reverse);

const lastAndUpper = compose(toUpperCase, head, reverse,);

console.log(last(["jumpkick", "roundhouse", "uppercut"]));
// "uppercut"
console.log(lastAndUpper(["jumpkick", "roundhouse", "uppercut"]))
// "UPPERCUT"

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

作者最新文章