前端 Javascript 高效开发工具函数

15,400 阅读14分钟

一、数组

multArray多维数组转换

将数组(array)拆分成多个子数组,并将这些子数组组成一个新数组。

multArray(array, count)

参数

  • array需要处理的数组
  • count = 8子数组需要的长度

示例

multArray([1, 2, 3, 4, 5, 6], 2)
=> [[1, 2], [3, 4], [5, 6]]

multArray(['a', 'b', 'c', 'd'], 3)
=> [['a', 'b', 'c'], ['d']]

源码

function multArray(input, size) {
    return input.reduce((arr, item, idx) => {
        return idx % size === 0
            ? [...arr, [item]]
            : [...arr.slice(0, -1), [...arr.slice(-1)[0], item]];
    }, []);
};

flatten扁平化数组

将多层嵌套数组(array)拆分成一个数组

flatten(array)

参数

  • array多层嵌套数组

示例

flatten([1, [2], [3], [4, 5]])
=> [1, 2, 3, 4, 5]

源码

// 扁平化 Map 方法
function flatten(array) {
    return [].concat(...array.map(item => {
        return Array.isArray(item) ? flatten(item) : item;
    }));
};

// 扁平化 reduce 方法
function flatten(array) {
    return array.reduce((arr, i) => {
        return arr.concat(Array.isArray(i) ? flatten(i) : i);
    }, []);
};

flattenDeep指定层级扁平化数组

将多层嵌套数组(array)拆分成指定层级数组

flattenDeep(array, depth)

参数

  • array多层嵌套数组
  • depth = 减少的嵌套层级数

示例

flattenDeep(['a', ['b', ['c', ['d']], 'e']], 1)
=> ['a', 'b', ['c', ['d']], 'e']

// ES6方法 `flat(depth)`
['a', ['b', ['c', ['d']], 'e']].flat(1)
=> ['a', 'b', ['c', ['d']], 'e']

源码

function flattenDeep(array, depth) {
    return array.reduce((arr, i) => {
        return arr.concat((depth > 1 && Array.isArray(i)) ? flattenDeep(i, depth - 1) : i);
    }, []);
};

isArrayEqual检查两个数组各项相等

比较两个数组内的各项值是否相等,返回一个Boolean

isArrayEqual(arrOne, arrTwo)

参数

  • arrOne 要检查的数组
  • arrTwo 要检查的数组

示例

isArrayEqual([6, 5, 2, 4, 1, 3], [1, 2, 3, 4, 5, 6])
=> true

isArrayEqual([6, 5, 2, 7, 1, 3], [1, 2, 3, 4, 5, 6])
=> false

源码

function isArrayEqual(arrOne, arrTwo) {
    let res = true;
    if (arrOne.length !== arrTwo.length) {
        return res = false;
    };
    const s = new Set(arrTwo);
    if (arrOne.find(i => !s.has(i))) {
        return res = false;
    };
    return res;
};

allEqual检查数组各项相等

allEqual(array)

参数

  • array 要检查的数组

示例

allEqual([1, 2, 3, 4, 5, 6])
=> false

allEqual([1, 1, 1, 1])
=> true

源码

function allEqual(array) {
    return array.every(item => item === array[0])
}

diffArray具有唯一array值的数组

创建一个具有唯一 array 值的数组,每个值不包含在其他给定的数组中

diffArray(arrOne, arrTwo)

参数

  • arrOne 要检查的数组
  • arrTwo要排除的数组

示例

diffArray(['a', 2, 6, 7], ['a', 2, 9, 'b'])
=> [ 6, 7 ]

源码

function diffArray(arrOne, arrTwo) {
    const s = new Set(arrTwo);
    let arr = arrOne.filter(x => !s.has(x));
    return arr;
};

haveArr具有共同array值的数组

创建一个具有共同 array 值的数组,每个值包含在其他给定的数组中

haveArr(arrOne, arrTwo)

参数

  • arrOne 要检查的数组
  • arrTwo要包含的数组

示例

haveArr([1, 2, 6, 7], [1, 2, 9, 5])
=> [ 1, 2 ]

源码

function haveArr(arrOne, arrTwo) {
    const s = new Set(arrTwo);
    return arrOne.filter(i => s.has(i));
}

// ES6 includes
function haveArr(arrOne, arrTwo) {
    return arrOne.filter(v => arrTwo.includes(v));
}

uniqueArray数组去重

创建一个去重后的 array 数组副本

uniqueArray(array)

参数

  • array 要去重的数组

示例

uniqueArray([1, 2, 2, 3, 4, 4, 5])
=> [ 1, 2, 3, 4, 5 ]

源码

// 第一种
const uniqueArray = (...array) => [...new Set(array)];

// 第二种
const uniqueArray = (...array) => Array.from(new Set(array));

uniqueArrayObject数组对象去重

创建一个去重后的 array 数组对象副本

uniqueArrayObject(array)

参数

  • array 要去重的数组
  • key 要去重的对象属性值

示例

const responseList = [
    { id: 1, a: 1 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
    { id: 1, a: 4 },
]

uniqueArrayObject(responseList, 'id')
=> [
    { id: 1, a: 1 },
    { id: 2, a: 2 },
    { id: 3, a: 3 },
   ]

源码

function uniqueArrayObject(array, key) {
    return array.reduce((acc, cur) => {
        const ids = acc.map(i => i[key]);
        return ids.includes(cur[key]) ? acc : [...acc, cur];
    }, []);
};

treeData生成树结构数据

该函数传入一个数组, 每项id对应其父级数据parent_id,返回一个树结构数组

treeData(array, id, parent_id)

参数

  • array 要生成树结构的数组
  • id 自定义属性名
  • parent_id 父级自定义属性名

示例

const comments = [
    { id: 1, parent_id: null },
    { id: 2, parent_id: 1 },
    { id: 3, parent_id: 1 },
    { id: 4, parent_id: 2 },
    { id: 5, parent_id: 4 },
]

treeData(comments, id = null, link = "parent_id")
=> [{
    id: 1,
    parent_id: null,
    children: [{
        id: 2,
        parent_id: 1,
        children: [{
            id: 4,
            parent_id: 2,
            children: [{
                id: 5,
                parent_id: 4,
                children: [],
                }],
            }],
    }, {
    id: 3,
    parent_id: 1,
    children: [],
    }],
}]

源码

function treeData(array, id, link) {
    const newArr = array.filter(item => item[link] === id);
    return newArr.map(item => ({...item, children: treeData(array, item.id)}))
}

flatArrFunc树结构数据生成数组

该函数传入一个树结构数组,返回一个数组

flatArrFunc(arrayObj)

参数

  • arrayObj 要遍历树结构的数组

示例

const list = [ { id: 1, parent_id: null, children: [ { id: 2, parent_id: 1, children: [ { id: 4, parent_id: 2, children: [ { id: 5, parent_id: 4, children: [] } ] } ] }, { id: 3, parent_id: 1, children: [] } ] } ]

flatArrFunc(list)

=> [
    { id: 1, parent_id: null },
    { id: 2, parent_id: 1 },
    { id: 3, parent_id: 1 },
    { id: 4, parent_id: 2 },
    { id: 5, parent_id: 4 },
]

源码

function flatArrFunc(arrayObj) {
    let = array = [];
    for (const item of arrayObj) {
        const json = { ...item };
        if (item.children) {
            delete json.children;
        };
        array.push(json);
        if (item.children && item.children.length) {
            array = [].concat(array, flatArrFunc(item.children));
        };
    }
    return array;
};

ascArr数组升序

返回升序后的新数组

sort()方法会改变原数组,默认按 unicode 码顺序排列

ascArr(array)

参数

  • array 要检查的排序数组

示例

ascArr([3, 2, 3, 4, 1])
=> [ 1, 2, 3, 3, 4 ]

源码

// 通过ES6 ... 展开运算符浅拷贝一份新数组
const ascArr = arr => [...arr].sort((a,b) => a-b);

descArr数组降序

返回降序后的新数组

descArr(array)

参数

  • array 要检查的排序数组

示例

descArr([3, 2, 3, 4, 1])
=> [ 1, 2, 3, 3, 4 ]

源码

const descArr = arr => [...arr].sort((a, b) => b-a);

shuffle随机排序

创建一个随机的数组,使用Fisher-Yates算法随机排序数组的元素

shuffle(array)

参数

  • array 要随机的数组

示例

shuffle([2, 3, 1])
=> [3, 1, 2]

源码

function shuffle([...arr]) {
    let m = arr.length;
    while(m) {
        const i = Math.floor(Math.random() * m--);
        [arr[m], arr[i]] = [arr[i], arr[m]];
    };
    return arr;
};

takeArray截取数组开始指定的元素

从 array 数组的最开始一个元素开始提取 n 个元素

takeArray(array, n)

参数

  • array要检索的数组。
  • n=要提取的元素n个数。

示例

takeArray([2, 3, 1], 2)
=> [2, 3]

源码

function takeArray(arr, n) {
    return arr.slice(0, n);
};

takeLastArray截取数组最后指定的元素

从 array 数组的最后一个元素开始提取 n 个元素

takeLastArray(array, n)

参数

  • array要检索的数组。
  • n=要提取的元素n个数。

示例

takeLastArray([2, 3, 1], 2)
=> [3, 1]

源码

function takeLastArray(arr, n) {
    return arr.slice(n * -1);
}

cloneArray克隆数组

浅拷贝一份数组副本

cloneArray(array)

参数

  • array要复制的数组

示例

cloneArray([1, 24])
=> [1, 24]

源码

// ES6 ...
const cloneArray = arr => [...arr];

// ES6 Array.from
const cloneArray = arr => Array.from(arr);

// concat()
const cloneArray = arr => [].concat(arr);

// map()
const cloneArray = arr => arr.map(i => i);

maxArray数组中最大值

过滤原数组中所有的非假值元素,返回数组中的最大值

maxArray(array)

参数

  • array待处理的数组

示例

maxArray([0, -1, -2, -3, false])
=> 0

源码

function maxArray(arr) {
    return Math.max(...arr.filter(v => Boolean(v) || v === 0));
}

minArray数组中最小值

过滤原数组中所有的非假值元素,返回数组中的最小值

minArray(array)

参数

  • array待处理的数组

示例

minArray([0, -1, -2, -3, false])
=> -3

源码

function minArray(arr) {
    return Math.min(...arr.filter(v => Boolean(v) || v === 0));
}

validArray去除数组中的无效值

创建一个新数组,包含原数组中所有的非假值元素。例如false, null,0, "", undefined, 和 NaN 都是被认为是“假值”。

validArray(array)

参数

  • array待处理的数组

示例

validArray([0, 1, false, 2, '', 3])
=> [1, 2, 3]

源码

const validArray = arr => arr.filter(Boolean);

filterParams去除请求参数中的无效值

创建一个新的请求参数,包含原请求参数中所有的无效值元素。例如, null, "", undefined, 和 NaN 都是被认为是“无效值”。

filterParams(obj)

参数

  • obj待处理的请求参数

示例

const params = {
    a:1,
    b: '2',
    c: null,
    d: '',
    e: undefined,
    f: NaN,
}
filterParams(params)
=> {a: 1, b: '2'}

源码

function filterParams(obj) {
    let _newPar = {};
    for (let key in obj) {
        if((obj[key] === 0 || obj[key] === false || obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, "") !== "") {
            _newPar[key] = obj[key];
        };
    };
    return _newPar;
};

二、对象

cloneObject克隆对象

浅拷贝一份对象副本

cloneObject(object)

参数

  • object要复制的对象

示例

const a = { x: 1, y: 1 }
const b = cloneObject(a)
=> a !== b

源码

// ES6 ...
const cloneObject = (obk, temp = {}) => (temp = { ...obj });

// Object.assign()
const cloneObject = obj => Object.assign({}, obj);

三、函数

debounce函数防抖

在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。

debounce(fn, wait)

参数

  • fn 要防抖动的函数
  • wait=500需要延迟的毫秒数

示例

debounce(()=> { console.log('debounce') }, 1000)
=> 1秒后打印'debounce'

源码

const debounce = (() => {
    let timer = {};
    return function(func, wait = 500) {
        let = context = this; // 注意this指向
        let args = arguments; // arguments中存在e
        let name = arguments[0].name || "arrow"; // 箭头函数
        !!(timer[name]) && clearTimeout(timer[name]);
        timer[name] = setTimeout(() => {
            func.apply(this, args);
        }, wait);
    };
})();

throttle函数节流

规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。

throttle(fn, wait)

参数

  • fn 要节流的函数
  • wait=500需要延迟的毫秒数

示例

throttle(() => {
    console.log('throttle')
}, 1000)
=> 1秒多次触发打印一次`throttle`

源码

const throttle = (() => {
    let tomeout = null;
    return function(func, wait) {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimeout(() => {
                timeout = null;
                func.apply(context, args);
            }, wait);
        };
    };
})();

typeFn类型判断

判断是否是 Array Object String Number Boolean Null Function 类型

typeFn.type(value)

参数

  • type 数据类型
  • value要检验的值

示例

typeFn.String('1')
typeFn.Number(1)
typeFn.Boolean(false)
typeFn.Null(null)
typeFn.Array([1, 2])
typeFn.Object({ a: 1 })
typeFn.Function(() => {})

=> true

源码

let typeFn = {};
const curring = (fn, arr = []) => {
    let len = fn.length;
    return (...args) => {
        arr = arr.concat(args);
        if (arr.length < len) {
            return curring(fn, arr);
        };
        return fn(...arr);
    };
};
const isType = (type, content) => Object.prototype.toString.call(content) === `[object ${type}]`;
["String", "Number", "Boolean", "Null", "Array", "Object", "Function"].forEach(item => {
    typeFn[item] = curring(isType)(item);
});

calcFn加减乘除运算

因为 JavaScript 遵循 IEEE 754 数学标准,使用 64 位浮点数进行运算。在进行十进制运算时会导致精度丢失。

calcFn.add(value1, value2, value3)

参数

  • addsubmuldiv运算符
  • value要计算的值

示例

解决 0.1+0.2 !== 0.3 问题
//加法
calcFn.add(0.1, 0.2)
=> 0.3

//减法
calcFn.sub(0.1, 0.2)
=> 0.1

//乘法
calcFn.mul(0.2, 0.3)
=> 0.06

// 除法
calcFn.div(0.1, 0.2)
=> 0.5

源码

const calcFn = {
    add() {
        let arg = Array.from(arguments);
        return arg.reduce((total, num) => accAdd(total, num));
    },
    sub() {
        let arg = Array.from(arguments);
        return arg.reduce((total, num) => accAdd(total, num * -1));
    },
    mul() {
        let arg = Array.from(arguments);
        return arg.reduce((total, num) => accMul(total, num));
    },
    div() {
        let arg = Array.from(arguments);
        return arg.reduce((total, num) => accDiv(total, num));
    },
};
const accAdd = (arg1, arg2) => {
    let r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    };
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    };
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
};
const accMul = (arg1, arg2) => {
    let m = 0;
    let s1 = arg1.toString();
    let s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) { };
    try {
        m += s2.split(".")[1].length;
    } catch (e) { };
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
};
const accDiv = (arg1, arg2) => {
    let s1 = arg1.toString();
    let s2 = arg2.toString();
    let t1 = 0;
    let t2 = 0;
    let r1;
    let r2;
    try {
        t1 = s1.split(".")[1].length;
    } catch (e) { };
    try {
        t2 = s2.split(".")[1].length;
    } catch (e) { };
    r1 = Number(s1.replace(".", ""));
    r2 = Number(s2.replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
};

四、字符串

isNil值是否是nullundefined

isNil(value)

参数

  • value 要检验的值

示例

isNil(null)
isNil(undefined)
=> true

源码

const isNil = val => (val === undefined || val === null);

padStart遮住字符串

padStart(value, n, maskChar)

参数

  • value 要遮住字符串
  • n = 4 填充的长度
  • maskChar 填充字符

示例

padStart('18659808664', n = 3, maskChar = "*")
=> 186********

源码

function padStart(str, n, maskChar) {
    return str.slice(0, n).padStart(str.length, maskChar);
};

五、数字

thousands数字每隔三位数加分号

thousands(number)

参数

  • number 数字或者浮点数

示例

thousands(12255552323)
=> 12,255,552,323

thousands(592535.2641)
=> 592,535.2641

源码

function thousands(num) {
    const numStr = num.toString();
    return numStr.replace(numStr.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g, "$1,");
};

numPercentage将小数转化为百分数

numPercentage(number,digit)

参数

  • number 小数
  • digit 保留位数

示例

numPercentage(12.655566, 3)
=> 1265.557%

源码

function numPercentage(num, digit) {
    let res = "";
    res = `${(Math.abs(Number(num) * 100)).toFixed(digit)}%`;
    return res;
};

randomNumber指定范围的随机整数

randomNumber(min, max)

参数

  • min 指定范围最小值
  • max 指定范围最大值

示例

randomNumber(0, 10)
=> 7
=> 2

源码

function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

average求平均值

average(value1, value2, value3)

参数

  • value 数字

示例

average(...[1, 2, 3])
average(1, 2, 3)
=> 2

源码

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;

averageBy求数组对象内某对象的平均值

averageBy(array, fn)

参数

  • array 要迭代的数组
  • fn 迭代函数

示例

averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n)
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n')
=> 5

源码

function averageBy(arr, fn) {
    return arr.map(typeof fn === "function" ? fn : (val => val[fn])).reduce((acc, val) => acc + val, 0) / arr.length;
};

aboutEqual两个值是否约等于

传入两个数字是否大致相等,误差在可接受范围内

aboutEqual(n1, n2, epsilon)

参数

  • n1 n2 要比较的数字
  • epsilon 误差可接受范围内

示例

aboutEqual(25, 2, 0.06)
=> false

源码

function aboutEqual(n1, n2, epsilon) {
    return Math.abs(n1 - n2) < epsilon;
}

getLineSize计算两点之间的距离

勾股定理计算两点之间的距离

getLineSize = (x1, y1, x2, y2)

参数

  • x1 y1 x2 y2坐标点

示例

getLineSize(0, 0, 3, 4)
=> 5

源码

function getLineSize(x1, y1, x2, y2) {
    return Math.hypot(x2 - x1, y2 - y1);
}

sum数组中值总和

sum(value1, value2, value3)

参数

  • value1 value2 value3要迭代的数字

示例

sum(1, 2, 3, 4)
sum(...[1, 2, 3, 4])
=> 10

源码

function sum(...arr) {
    return [...arr].reduce((acc, val) => acc + val, 0);
};

六、浏览器

copyTextH5复制文本

copyText(content, callback)

参数

  • content要复制文字
  • callback 回调用户提示

示例

copyText(content, text => {
    console.log(text)
})

源码

const copyText = (context, callback) => {
    if (!document.queryCommandSupported("copy")) {
        // 为了兼容有些浏览器 queryCommandSupported 的判断
        console.log("浏览器不支持");
        return;
    }
    let textarea = document.createElement("textarea");
    textarea.value = context;
    textarea.readOnly = "readOnly";
    document.body.appendChild(textarea);
    textarea.select(); // 选择对象
    textarea.setSelectionRange(0, context.length); // 核心
    let result = document.execCommand("copy"); // 执行浏览器复制命令
    !!callback && callback(result ? "复制成功~" : "复制失败~");
    textarea.remove();
};

getCurrentURL获取当前的 URL 地址

该函数返回当前页面的 URL 地址。

示例

getCurrentURL()
=> "https://juejin.cn"

源码

const getCurrentURL = () => window.location.href;

scrollToTop返回顶部

平滑地滚动到当前页面的顶部。

示例

scrollToTop()
=> 当前页面的顶部

源码

function scrollToTop() {
    const c = document.documentElement.scrollTop || document.body.scrollTop;
    console.log(c)
    if (c > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, c - c / 8);
    };
};

smoothScroll平滑滚动页面

平滑滚动到浏览器窗口的可见区域

示例

smoothScroll('#fooBar');
=> 平滑滚动到ID为fooBar的元素
smoothScroll('.fooBar' );
=> 使用fooBar类平滑滚动到第一个元素

源码

const smoothScroll = element => document.querySelector(element).scrollIntoView({ behavior: "smooth" });

isCurrentPage是否是当前页面

浏览器的选项卡是否是用户在浏览

示例

isCurrentPage()
=> true

源码

const isCurrentPage = () => !document.hidden;

七.环境

isBrowser是否是浏览器

返回当前运行时环境是否为浏览器

示例

isBrowser()
=> true (browser)
=> false (Node)

源码

const isBrowser = () => ![typeof window, typeof document].includes("undefined");

isWechatBrowser判断微信浏览器还是普通h5

示例

isWechatBrowser()
=> true

源码

const isWechatBrowser = () => {
    let ua = navigator.userAgent.toLowerCase();
    return /micromessenger/.test(ua);
}

isMobile判断是否是移动端

示例

isMobile()
=> true

源码

function isMobile() {
    return /Android|webOs|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent);
}

八、其他

after

此方法创建一个函数,当他被调用n或更多次之后将马上触发func

after(n, func)

参数

  • n(number): func 方法应该在调用多少次后才执行。
  • func(Function): 用来限定的函数。

返回

(Function): 返回新的限定函数。

示例

const saves = ['profile', 'settings']
const done = after(saves.length, () => console.log('done saving!'))
 
forEach(saves, type => asyncSave({ 'type': type, 'complete': done }))
=> 打印 'done saving!' 在两个异步保存完成后。

源码

function after(n, func) {
    if (typeof func !== 'function') {
        throw new TypeError('Expected a function');
    };
    n = n || 0;
    return (...args) => {
        if (--n < 1) {
            return func.apply(this, args);
        };
    };
};

before

创建一个调用func的函数,通过this绑定和创建函数的参数调用func,调用次数不超过 n 次。 之后再调用这个函数,将返回一次最后调用func的结果。

before(n, func)

参数

  • n(number): 超过多少次不再调用func(注:限制调用func的次数)。
  • func(Function): 限制执行的函数。

返回

(Function): 返回新的限定函数。

示例

jQuery(element).on('click', _.before(5, addContactToList));
=> 最多只允许点击4

源码

function before(n, func) {
    let result;
    if (typeof func !== 'function') {
        throw new TypeError('Expected a function');
    };
    return function (...args) {
        if (--n > 0) {
            result = func.apply(this, args);
        };
        if (n <= 1) {
            func = undefined;
        };
        return result;
    };
};

castArray

创建一个调用func的函数,通过this绑定和创建函数的参数调用func,调用次数不超过 n 次。 之后再调用这个函数,将返回一次最后调用func的结果。

castArray(value)

参数

  • value(*): 要处理的值。

返回

(Array): 返回转换后的数组。

示例

castArray(1);
=> [1]
 
castArray({ 'a': 1 });
=> [{ 'a': 1 }]
 
castArray('abc');
=> ['abc']
 
castArray(null);
=> [null]
 
castArray(undefined);
=> [undefined]
 
castArray();
=> []
 
const array = [1, 2, 3];
console.log(castArray(array) === array);
=> true

源码

const castArray = (...args) => {
    if (!args.length) {
        return [];
    };
    const value = args[0];
    return Array.isArray(value) ? value : [value];
};

clamp

返回限制在 lowerupper 之间的值。

clamp(number, [lower], upper)

参数

  • number (number): 被限制的值。
  • [lower] (number): 下限。
  • upper (number): 上限。

返回

(number): 返回被限制的值。

示例

clamp(-10, -5, 5);
=> -5
 
clamp(10, -5, 5);
=> 5

源码

function clamp(number, lower, upper) {
    number = +number;
    lower = +lower;
    upper = +upper;
    lower = lower === lower ? lower : 0;
    upper = upper === upper ? upper : 0;
    if (number === number) {
        number = number <= upper ? number : upper;
        number = number >= lower ? number : lower;
    };
    return number;
};

compact

创建一个新数组,包含原数组中所有的非假值元素。例如false, null,0, "",undefined, 和 NaN 都是被认为是“假值”。

compact(array)

参数

  • array (Array): 待处理的数组

返回

(Array): 返回过滤掉假值的新数组。

示例

compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]

源码

function compact(array) {
    let resIndex = 0;
    const result = [];
    if (!Array.isArray(array)) {
        return result;
    };
    for (const value of array) {
        if (value) {
            result[resIndex++] = value;
        };
    };
    return result;
};

create

创建一个继承 prototype 的对象。 如果提供了 prototype,它的可枚举属性会被分配到创建的对象上。

create(prototype, [properties])

参数

  • prototype (Object): 要继承的对象。
  • [properties] (Object): 待分配的属性。

返回

(Object): 返回新对象。

示例

function Shape() {
  this.x = 0;
  this.y = 0;
}
 
function Circle() {
  Shape.call(this);
}
 
Circle.prototype = create(Shape.prototype, {
  'constructor': Circle
});
 
let circle = new Circle;
circle instanceof Circle;
=> true
 
circle instanceof Shape;
=> true

源码

function create(prototype, properties) {
    prototype = prototype === null ? null : Object(prototype);
    const result = Object.create(prototype);
    return properties == null ? result : Object.assign(result, properties);
};

defaultTo

检查value,以确定一个默认值是否应被返回。如果valueNaN, null, 或者 undefined,那么返回defaultValue默认值。

defaultTo(value, defaultValue)

参数

  • value (*): 要检查的值。
  • defaultValue (*): 默认值。

返回

(*): 返回 resolved 值。

示例

defaultTo(1, 10);
=> 1
 
defaultTo(undefined, 10);
=> 10

源码

function defaultTo(value, defaultValue) {
    return (value == null || value !== value) ? defaultValue : value;
};

defer

推迟调用func,直到当前堆栈清理完毕。 调用时,任何附加的参数会传给func

defer(func, [args])

参数

  • func (Function): 要延迟的函数。
  • [args] (...*): 会在调用时传给 func 的参数。

返回

(number):返回计时器 id。

示例

defer(function(text) {
  console.log(text);
}, 'deferred');
=> 一毫秒或更久一些输出 'deferred'

源码

function defer(func, ...args) {
    if (typeof func !== 'function') {
    throw new TypeError('Expected a function');
    };
    return setTimeout(func, 1, ...args);
};

delay

延迟 wait 毫秒后调用 func。 调用时,任何附加的参数会传给func

delay(func, wait, [args])

参数

  • func (Function): 要延迟的函数。
  • wait (number): 要延迟的毫秒数。
  • [args] (...*): 会在调用时传入到 func 的参数。

返回

(number): 返回计时器 id

示例

delay(function(text) {
  console.log(text);
}, 1000, 'later');
=> 一秒后输出 'later'

源码

function delay(func, wait, ...args) {
    if (typeof func !== 'function') {
        throw new TypeError('Expected a function');
    };
    return setTimeout(func, +wait || 0, ...args);
};

endsWith

检查字符串string是否以给定的target字符串结尾。

endsWith([string=''], [target], [position=string.length])

参数

  • [string=''] (string): 要检索的字符串。
  • [target] (string): 要检索字符。
  • [position=string.length] (number): 检索的位置。

返回

(boolean): 如果字符串stringtarget字符串结尾,那么返回 true,否则返回 false

示例

endsWith('abc', 'c');
=> true
 
endsWith('abc', 'b');
=> false
 
endsWith('abc', 'b', 2);
=> true

源码

function endsWith(string, target, position) {
    const { length } = string;
    position = position === undefined ? length : +position;
    if (position < 0 || position != position) {
        position = 0;
    } else if (position > length) {
        position = length;
    };
    const end = position;
    position -= target.length;
    return position >= 0 && string.slice(position, end) == target;
};

eq

执行SameValueZero 比较两者的值,来确定它们是否相等。

eq(value, other)

参数

  • value (*): 要比较的值。
  • other (*): 另一个要比较的值。

返回

(boolean): 如果两个值相等返回 true ,否则返回 false

示例

let object = { 'a': 1 };
let other = { 'a': 1 };
 
eq(object, object);
=> true
 
eq(object, other);
=> false
 
eq('a', 'a');
=> true
 
eq('a', Object('a'));
=> false
 
eq(NaN, NaN);
=> true

源码

function eq(value, other) {
    return value === other || (value !== value && other !== other);
};

图片懒加载

intersectionObserver 的实现方式,实例化一个 IntersectionObserver ,并使其观察所有 img 标签。当 img 标签进入可视区域时会执行实例化时的回调,同时给回调传入一个 entries 参数,保存着实例观察的所有元素的一些状态,比如每个元素的边界信息,当前元素对应的 DOM 节点,当前元素进入可视区域的比率,每当一个元素进入可视区域,将真正的图片赋值给当前 img 标签,同时解除对其的观察。

源码

let imgArr = [...document.querySelectorAll("img")];

let lazyLoadImg = function() {
    let observer = new IntersectionObserver(entries => {
        entries.forEach(entry => {
            if (entry.intersectionRatio > 0) {
                entry.target.src = entry.target.dataset.src;
                observer.unobserve(entry.target);
            };
        });
    });
    imgArr.forEach(img => {
        observer.observe(img);
    });
}