今天,學(xué)會這10個JS代碼段就夠了!
作者:maomin9761
在本文中,我們來看一下,如何學(xué)會這10個JS代碼段,讓我們一起學(xué)習(xí)一下吧!
用 apply 將數(shù)組各項添加到另一個數(shù)組
- const array = ['a', 'b'];
- const elements = [0, 1, 2];
- array.push.apply(array, elements);
- console.info(array); // ["a", "b", 0, 1, 2]
函數(shù)只執(zhí)行一次
- function once (fn){
- let called = false
- return function () {
- if (!called) {
- called = true
- fn.apply(this, arguments)
- }
- }
- }
- function func (){
- console.log(1);
- }
- //調(diào)用
- let onlyOnce = once(func);
- // 測試
- onlyOnce(); // 1
- onlyOnce(); // 不執(zhí)行
防抖
- /**
- * 防抖
- * @param {Function} func 要執(zhí)行的回調(diào)函數(shù)
- * @param {Number} wait 延時的時間
- * @param {Boolean} immediate 是否立即執(zhí)行
- * @return null
- */
- let timeout;
- function Debounce(func, wait = 3000, immediate = true) {
- // 清除定時器
- if (timeout !== null) clearTimeout(timeout);
- // 立即執(zhí)行,此類情況一般用不到
- if (immediate) {
- var callNow = !timeout;
- timeout = setTimeout(function() {
- timeout = null;
- }, wait);
- if (callNow) typeof func === 'function' && func();
- } else {
- // 設(shè)置定時器,當(dāng)最后一次操作后,timeout不會再被清除,所以在延時wait毫秒后執(zhí)行func回調(diào)方法
- timeout = setTimeout(function() {
- typeof func === 'function' && func();
- }, wait);
- }
- }
- Debounce(()=>console.log(1));
遞歸數(shù)組降為一維
- let children = [1, [2, 3], [4, [5, 6, [7, 8]]], [9, 10]];
- function simpleNormalizeChildren(children) {
- for (let i = 0; i < children.length; i++) {
- if (Array.isArray(children[i])) {
- children = Array.prototype.concat.apply([], children);
- simpleNormalizeChildren(children)
- }
- }
- return children;
- }
- console.log(simpleNormalizeChildren(children)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
數(shù)組降維(二維降一維)
- function simpleNormalizeChildren(children) {
- for (let i = 0; i < children.length; i++) {
- if (Array.isArray(children[i])) {
- return Array.prototype.concat.apply([], children)
- }
- }
- return children
- }
- let arrs = [['1'],['3']];
- const arr = simpleNormalizeChildren(arrs);
- console.log(arr); // ['1','3']
使用可選鏈進(jìn)行函數(shù)調(diào)用
- function doSomething(onContent, onError) {
- try {
- // ... do something with the data
- }
- catch (err) {
- onError?.(err.message); // 如果onError是undefined也不會有異常
- }
- }
檢測數(shù)組對象中是否有空值
- const data = [
- {
- name:"maomin"
- },
- {
- name:""
- }
- ]
- const arr = data.filter(item =>
- Object.values(item).includes('')
- );
- console.log(arr.length>0?"有空值":"無空值"); // 有空值
計算數(shù)組中每個元素出現(xiàn)的次數(shù)
- let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
- let countedNames = names.reduce(function (allNames, name) {
- if (name in allNames) {
- allNames[name]++;
- }
- else {
- allNames[name] = 1;
- }
- return allNames;
- }, {});
- console.log(countedNames); // { Alice: 2, Bob: 1, Tiff: 1, Bruce: 1 }
按屬性對object分類
- let people = [
- { name: 'Alice', age: 21 },
- { name: 'Max', age: 20 },
- { name: 'Jane', age: 20 }
- ];
- function groupBy(objectArray, property) {
- return objectArray.reduce(function (acc, obj) {
- let key = obj[property];
- if (!acc[key]) {
- acc[key] = [];
- }
- acc[key].push(obj);
- return acc;
- }, {});
- }
- const groupedPeople = groupBy(people, 'age');
- console.log(groupedPeople);
- // {
- // 20: [
- // { name: 'Max', age: 20 },
- // { name: 'Jane', age: 20 }
- // ],
- // 21: [{ name: 'Alice', age: 21 }]
- // }
將帶有分割符的字符串轉(zhuǎn)化成一個n維數(shù)組
- const str = "A-2-12";
- const str1 = str.split('-');
- console.log(str1);
- const arr = str1.reverse().reduce((pre,cur,i) => {
- if(i==0)
- { pre.push(cur)
- return pre
- }
- return [cur,pre]
- },[])
- console.log(arr) // ["A"["B",["C"]]]
本文轉(zhuǎn)載自微信公眾號「前端歷劫之路」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系前端歷劫之路公眾號。
責(zé)任編輯:武曉燕
來源:
前端歷劫之路