首页 文章详情

不想加班,你就背会这 10 条 JS 技巧

全栈修炼 | 159 2021-11-07 13:38 0 0 0
UniSMS (合一短信)
为了让自己写的代码更优雅且高效,特意向大佬请教了这 10 条 JS 技巧

1. 数组分割

const listChunk = (list = [], chunkSize = 1) => {
    const result = [];
    const tmp = [...list];
    if (!Array.isArray(list) || !Number.isInteger(chunkSize) || chunkSize <= 0) {
        return result;
    };
    while (tmp.length) {
        result.push(tmp.splice(0, chunkSize));
    };
    return result;
};
listChunk(['a''b''c''d''e''f''g']);
// [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g']]

listChunk(['a''b''c''d''e''f''g'], 3);
// [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

listChunk(['a''b''c''d''e''f''g'], 0);
// []

listChunk(['a''b''c''d''e''f''g'], -1);
// []

2. 求数组元素交集

const listIntersection = (firstList, ...args) => {
    if (!Array.isArray(firstList) || !args.length) {
        return firstList;
    }
    return firstList.filter(item => args.every(list => list.includes(item)));
};
listIntersection([12], [34]);
// []

listIntersection([22], [34]);
// []

listIntersection([32], [34]);
// [3]

listIntersection([34], [34]);
// [3, 4]

3. 按下标重新组合数组

const zip = (firstList, ...args) => {
    if (!Array.isArray(firstList) || !args.length) {
        return firstList
    };
    return firstList.map((value, index) => {
        const newArgs = args.map(arg => arg[index]).filter(arg => arg !== undefined);
        const newList = [value, ...newArgs];
        return newList;
    });
};
zip(['a''b'], [12], [truefalse]);
// [['a', 1, true], ['b', 2, false]]

zip(['a''b''c'], [12], [truefalse]);
// [['a', 1, true], ['b', 2, false], ['c']]

4. 按下标组合数组为对象

const zipObject = (keys, values = {}) => {
    const emptyObject = Object.create({});
    if (!Array.isArray(keys)) {
        return emptyObject;
    };
    return keys.reduce((acc, cur, index) => {
        acc[cur] = values[index];
        return acc;
    }, emptyObject);
};
zipObject(['a''b'], [12])
// { a: 1, b: 2 }
zipObject(['a''b'])
// { a: undefined, b: undefined }

5. 检查对象属性的值

const checkValue = (obj = {}, objRule = {}) => {
    const isObject = obj => {
        return Object.prototype.toString.call(obj) === '[object Object]';
    };
    if (!isObject(obj) || !isObject(objRule)) {
        return false;
    }
    return Object.keys(objRule).every(key => objRule[key](obj[key]));
};

const object = { a1b2 };

checkValue(object, {
    bn => n > 1,
})
// true

checkValue(object, {
    bn => n > 2,
})
// false

6. 获取对象属性

const get = (obj, path, defaultValue) => {
    if (!path) {
        return;
    };
    const pathGroup = Array.isArray(path) ? path : path.match(/([^[.\]])+/g);
    return pathGroup.reduce((prevObj, curKey) => prevObj && prevObj[curKey], obj) || defaultValue;
};

const obj1 = { a: { b2 } }
const obj2 = { a: [{ bar: { c3 } }] }

get(obj1, 'a.b')
// 2
get(obj2, 'a[0].bar.c')
// 3
get(obj2, ['a', '0', 'bar', 'c'])
// 2
get(obj1, 'a.bar.c', 'default')
// default
get(obj1, 'a.bar.c', 'default')
// default

7. 将特殊符号转成字体符号

const escape = str => {
    const isString = str => {
        return Object.prototype.toString.call(str) === '[string Object]';
    };
    if (!isString(str)) {
        return str;
    }
    return (str.replace(/&/g'&amp;')
      .replace(/"/g'&quot;')
      .replace(/'/g'&#x27;')
      .replace(/</g'&lt;')
      .replace(/>/g'&gt;')
      .replace(/\//g'&#x2F;')
      .replace(/\\/g'&#x5C;')
      .replace(/`/g'&#96;'));
};

8. 利用注释创建一个事件监听器

class EventEmitter {
    #eventTarget;
    constructor(content = '') {
        const comment = document.createComment(content);
        document.documentElement.appendChild(comment);
        this.#eventTarget = comment;
    }
    on(type, listener) {
        this.#eventTarget.addEventListener(type, listener);
    }
    off(type, listener) {
        this.#eventTarget.removeEventListener(type, listener);
    }
    once(type, listener) {
        this.#eventTarget.addEventListener(type, listener, { oncetrue });
    }
    emit(type, detail) {
        const dispatchEvent = new CustomEvent(type, { detail });
        this.#eventTarget.dispatchEvent(dispatchEvent);
    }
};

const emmiter = new EventEmitter();
emmiter.on('biy', () => {
    console.log('hello world');
});
emmiter.emit('biu');
// hello world

9. 生成随机的字符串

const genRandomStr = (len = 1) => {
    let result = '';
    for (let i = 0; i < len; ++i) {
        result += Math.random().toString(36).substr(2)
    }
    return result.substr(0, len);
}
genRandomStr(3)
// u2d
genRandomStr()
// y
genRandomStr(10)
// qdueun65jb

10. 判断是否是指定的哈希值

const isHash = (type = '', str = '') => {
    const isString = str => {
        return Object.prototype.toString.call(str) === '[string Object]';
    };
    if (!isString(type) || !isString(str)) {
        return str;
    };
    const algorithms = {
        md532,
        md432,
        sha140,
        sha25664,
        sha38496,
        sha512128,
        ripemd12832,
        ripemd16040,
        tiger12832,
        tiger16040,
        tiger19248,
        crc328,
        crc32b8,
    };
    const hash = new RegExp(`^[a-fA-F0-9]{${algorithms[type]}}$`);
    return hash.test(str);
};

isHash('md5''d94f3f016ae679c3008de268209132f2');
// true
isHash('md5''q94375dj93458w34');
// false

isHash('sha1''3ca25ae354e192b26879f651a51d92aa8a34d8d3');
// true
isHash('sha1''KYT0bf1c35032a71a14c2f719e5a14c1');
// false

后记

如果你喜欢探讨技术,或者对本文有任何的意见或建议,非常欢迎加鱼头微信好友一起探讨,当然,鱼头也非常希望能跟你一起聊生活,聊爱好,谈天说地。

全文完



有段时间没更新文章了,因为最近在跳槽,所以一直没空写文章,所以耽误了。


号主已经裸辞了 2 个月了,一直在面试大中小厂,共 40 场,有点想写两篇文章的,一篇是高频出现的 100 道前端试题及答案、还有一篇是这一路的心态变化及面试过程中的经验总结。


如果朋友们想看的,请给本文点个赞哦,我看看有多少人想看,我再决定要不要写。

good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter