js實現隨機生成4位數驗證碼
阿新 • • 發佈:2021-11-04
1.js實現隨機生成4位數驗證碼
const randomString = () => Math.random().toString(36).slice(2,6);
randomString();
//toString() 括號裡的內容代表進位制
2.翻轉字串
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'
3.陣列去重
const removeDuplicates = (arr) => [...new Set(arr)]; console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
4.合併陣列
const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];
5.獲得一組數的平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
6. 將RGB轉化為十六機制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(255, 255, 255); // '#ffffff'
7. 滾動到頁面頂部
const goToTop = () => window.scrollTo(0, 0);
goToTop();