不想加班,你就背會這 10 條 JS 技巧
為了讓自己寫的代碼更優(yōu)雅且高效,特意向大佬請教了這 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([1,?2],?[3,?4]);
//?[]
listIntersection([2,?2],?[3,?4]);
//?[]
listIntersection([3,?2],?[3,?4]);
//?[3]
listIntersection([3,?4],?[3,?4]);
//?[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'],?[1,?2],?[true,?false]);
//?[['a',?1,?true],?['b',?2,?false]]
zip(['a',?'b',?'c'],?[1,?2],?[true,?false]);
//?[['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'],?[1,?2])
//?{?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?=?{?a:?1,?b:?2?};
checkValue(object,?{
????b:?n?=>?n?>?1,
})
//?true
checkValue(object,?{
????b:?n?=>?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:?{?b:?2?}?}
const?obj2?=?{?a:?[{?bar:?{?c:?3?}?}]?}
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,?'&')
??????.replace(/"/g,?'"')
??????.replace(/'/g,?''')
??????.replace(/,?'<')
??????.replace(/>/g,?'>')
??????.replace(/\//g,?'/')
??????.replace(/\\/g,?'\')
??????.replace(/`/g,?'`'));
};
8. 利用注釋創(chuàng)建一個事件監(jiān)聽器
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,?{?once:?true?});
????}
????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?????????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?=?{
????????md5:?32,
????????md4:?32,
????????sha1:?40,
????????sha256:?64,
????????sha384:?96,
????????sha512:?128,
????????ripemd128:?32,
????????ripemd160:?40,
????????tiger128:?32,
????????tiger160:?40,
????????tiger192:?48,
????????crc32:?8,
????????crc32b:?8,
????};
????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 道前端試題及答案、還有一篇是這一路的心態(tài)變化及面試過程中的經驗總結。
如果朋友們想看的,請給本文點個贊哦,我看看有多少人想看,我再決定要不要寫。
評論
圖片
表情
