1 // 建立過去七天的數組,若是將代碼中的減號換成加號,你將獲得將來7天的數組集合 2 [...Array(7).keys()].map(days => new Date(Date.now() - 86400000 * days)); 3 4 // 生成長度爲11的隨機字母數字字符串 5 Math.random().toString(36).substring(2); 6 7 // 獲取URL的查詢參數 8 q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q; 9 10 // 建立本地時間 11 new Date().toLocaleString().slice(10,19) 12 13 // 隨機更改數組元素順序,混淆數組 隨機排序 14 (arr) => arr.slice().sort(() => Math.random() - 0.5) 15 16 // 生成隨機十六進制代碼 如:'#c618b2' 17 '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0'); 18 19 // 用字符串返回一個鍵盤圖形 20 (_=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x<y?2:' 667699'[x=["BS","TAB","CAPS","ENTER"][p++]||'SHIFT',p])}\\|`,m+=y+(x+' ').slice(0,w)+y+y,n+=y+b+y+y,l+=' __'+b)[73]&&(k.push(l,m,n,o),l='',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join` 21 `)()
1 //扁平化n維數組 2 [1,[2,3]].flat(2) //[1,2,3] 3 [1,[2,3,[4,5]].flat(3) //[1,2,3,4,5] 4 [1,[2,3,[4,5]]].toString() //'1,2,3,4,5' 5 [1[2,3,[4,5[...]].flat(Infinity) //[1,2,3,4...n] 6 7 //去重 8 Array.from(new Set([1,2,3,3,4,4])) //[1,2,3,4] 9 [...new Set([1,2,3,3,4,4])] //[1,2,3,4] 10 11 //最大值 12 Math.max(...[1,2,3,4]) //4 13 Math.max.apply(this,[1,2,3,4]) //4 14 [1,2,3,4].reduce( (prev, cur,curIndex,arr)=> { 15 return Math.max(prev,cur); 16 },0) //4 17 18 //求和 19 [1,2,3,4].arr.reduce(function (prev, cur) { 20 return prev + cur; 21 },0) //10 22 23 //合併 24 [1,2,3,4].concat([5,6]) //[1,2,3,4,5,6] 25 [...[1,2,3,4],...[4,5]] //[1,2,3,4,5,6] 26 [1,2,3,4].push.apply([1,2,3,4],[5,6]) //[1,2,3,4,5,6] 27 28 //判斷是否包含值 29 [1,2,3].includes(4) //false 30 [1,2,3].indexOf(4) //-1 若是存在換回索引 31 [1, 2, 3].find((item)=>item===3)) //3 若是數組中無值返回undefined 32 [1, 2, 3].findIndex((item)=>item===3)) //2 若是數組中無值返回-1 33 34 //類數組轉化 35 Array.prototype.slice.call(arguments) //arguments是類數組(僞數組) 36 Array.prototype.slice.apply(arguments) 37 Array.from(arguments) 38 [...arguments] 39 //類數組:表示有length屬性,可是不具有數組的方法 40 //call,apply:是改變slice裏面的this指向arguments,因此arguments也可調用數組的方法 41 //Array.from是將相似數組或可迭代對象建立爲數組 42 //...是將類數組擴展爲字符串,再定義爲數組 43 44 //全部項是否知足 45 [1,2,3].every(item=>{return item>2}) //false 46 47 //有一項知足 48 [1,2,3].some(item=>{return item>2}) //true 49 50 //每一項設置值 51 [1,2,3].fill(false) //[false,false,false] 52 53 //對象和數組轉化 54 Object.keys({name:'張三',age:14}) //['name','age'] 55 Object.values({name:'張三',age:14}) //['張三',14] 56 Object.entries({name:'張三',age:14}) //[[name,'張三'],[age,14]] 57 Object.fromEntries([name,'張三'],[age,14]) //ES10的api,Chrome不支持 , firebox輸出{name:'張三',age:14}