现代 JavaScript 编码技巧概览
以下内容主要源自今年从其他技术专家文章中汲取的经验,特此整理分享。
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");
}
}
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}
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
5. 运用 compose 进行函数组合
以下代码即为组合函数 compose 的定义。
const compose = function(f, g) {
return function(x) {
return f(g(x));
};
};
鉴于函数式编程的流行,如今 JS 代码中常见大量箭头函数嵌套如 ()=>()=>()=> 的形式。
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"
以上即为本文全部内容,希望对各位学习有所帮助,也欢迎多多支持本站。