<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
前言;
JavaScript ( JS ) 是一種具有函數優先的輕量級,解釋型或即時編譯型的程式語言。雖然它是作為開發Web 頁面的指令碼語言而出名的,但是它也被用到了很多非瀏覽器環境中等等。
export function formatDateTimeStamp(date, fmt) { // 格式化時間戳 : formatDateTimeStamp(new Date(time),'yyyy-MM-dd hh:mm:ss') if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } let o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() } for (let k in o) { if (new RegExp(`(${k})`).test(fmt)) { let str = o[k] + '' fmt = fmt.replace( RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str)) } } return fmt } function padLeftZero(str) { return ('00' + str).substr(str.length); } export function parseTime(time, cFormat) { if (arguments.length === 0) { return null } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date if (typeof time === 'object') { date = time } else { if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) { time = parseInt(time) } if ((typeof time === 'number') && (time.toString().length === 10)) { time = time * 1000 } date = new Date(time) } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { const value = formatObj[key] // Note: getDay() returns 0 on Sunday if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] } return value.toString().padStart(2, '0') }) return time_str }
export function formatTime(time, option) { if (('' + time).length === 10) { time = parseInt(time) * 1000 } else { time = +time } const d = new Date(time) const now = Date.now() const diff = (now - d) / 1000 if (diff < 30) { return '剛剛' } else if (diff < 3600) { // less 1 hour return Math.ceil(diff / 60) + '分鐘前' } else if (diff < 3600 * 24) { return Math.ceil(diff / 3600) + '小時前' } else if (diff < 3600 * 24 * 2) { return '1天前' } if (option) { return parseTime(time, option) } else { return ( d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '時' + d.getMinutes() + '分' ) } } function pluralize(time, label) { if (time === 1) { return time + label + ' ago' } return time + label + 's' + ' ago' } export function timeAgo(time) { const between = Date.now() / 1000 - Number(time) if (between < 3600) { return pluralize(~~(between / 60), ' minute') } else if (between < 86400) { return pluralize(~~(between / 3600), ' hour') } else { return pluralize(~~(between / 86400), ' day') } }
export function getQueryObject(url) { url = url == null ? window.location.href : url const search = url.substring(url.lastIndexOf('?') + 1) const obj = {} const reg = /([^?&=]+)=([^?&=]*)/g search.replace(reg, (rs, $1, $2) => { const name = decodeURIComponent($1) let val = decodeURIComponent($2) val = String(val) obj[name] = val return rs }) return obj } export function param2Obj(url) { const search = url.split('?')[1] if (!search) { return {} } return JSON.parse( '{"' + decodeURIComponent(search) .replace(/"/g, '\"') .replace(/&/g, '","') .replace(/=/g, '":"') .replace(/+/g, ' ') + '"}' ) }
function cleanArray(actual) { const newArray = [] for (let i = 0; i < actual.length; i++) { if (actual[i]) { newArray.push(actual[i]) } } return newArray } export function param(obj) { if (!obj) return '' return cleanArray( Object.keys(obj).map(key => { if (obj[key] === undefined) return '' return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]) }) ).join('&') } export function stringfyQueryStr(obj) { if (!obj) return ''; let pairs = []; for (let key in obj) { let value = obj[key]; if (value instanceof Array) { for (let i = 0; i < value.length; ++i) { pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i])); } continue;`在這裡插入程式碼片` } pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } return pairs.join('&'); } param({name:'1111',sex:'wwww'}) stringfyQueryStr({name:'1111',sex:'wwww'})
export const store = { // 本地儲存 set: function(name, value, day) { // 設定 let d = new Date() let time = 0 day = (typeof(day) === 'undefined' || !day) ? 1 : day // 時間,預設儲存1天 time = d.setHours(d.getHours() + (24 * day)) // 毫秒 localStorage.setItem(name, JSON.stringify({ data: value, time: time })) }, get: function(name) { // 獲取 let data = localStorage.getItem(name) if (!data) { return null } let obj = JSON.parse(data) if (new Date().getTime() > obj.time) { // 過期 localStorage.removeItem(name) return null } else { return obj.data } }, clear: function(name) { // 清空 if (name) { // 刪除鍵為name的快取 localStorage.removeItem(name) } else { // 清空全部 localStorage.clear() } } }
export const cookie = { // cookie操作【set,get,del】 set: function(name, value, day) { let oDate = new Date() oDate.setDate(oDate.getDate() + (day || 30)) document.cookie = name + '=' + value + ';expires=' + oDate + "; path=/;" }, get: function(name) { let str = document.cookie let arr = str.split('; ') for (let i = 0; i < arr.length; i++) { let newArr = arr[i].split('=') if (newArr[0] === name) { return newArr[1] } } }, del: function(name) { this.set(name, '', -1) } }
export function numberFormatter(num, digits) { const si = [{ value: 1E18, symbol: 'E' }, { value: 1E15, symbol: 'P' }, { value: 1E12, symbol: 'T' }, { value: 1E9, symbol: 'G' }, { value: 1E6, symbol: 'M' }, { value: 1E3, symbol: 'k' } ] for (let i = 0; i < si.length; i++) { if (num >= si[i].value) { return (num / si[i].value).toFixed(digits).replace(/.0+$|(.[0-9]*[1-9])0+$/, '$1') + si[i].symbol } } return num.toString() }
export function toThousandFilter(num) { let targetNum = (num || 0).toString() if (targetNum.includes('.')) { let arr = num.split('.') return arr[0].replace(/^-?d+/g, m => m.replace(/(?=(?!b)(d{3})+$)/g, ',')) + '.' + arr[1] } else { return targetNum.replace(/^-?d+/g, m => m.replace(/(?=(?!b)(d{3})+$)/g, ',')) } }
export function versionFilter(versions) { let v0 = (versions & 0xff000000) >> 24 let v1 = (versions & 0xff0000) >> 16 let v2 = (versions & 0xff00) >> 8 let v3 = versions & 0xff return `${v0}.${v1}.${v2}.${v3}` }
export function uppercaseFirst(string) { return string.charAt(0).toUpperCase() + string.slice(1) }
export function hasClass(ele, cls) { return !!ele.className.match(new RegExp('(\s|^)' + cls + '(\s|$)')) } export function addClass(ele, cls) { if (!hasClass(ele, cls)) ele.className += ' ' + cls } export function removeClass(ele, cls) { if (hasClass(ele, cls)) { const reg = new RegExp('(\s|^)' + cls + '(\s|$)') ele.className = ele.className.replace(reg, ' ') } }
const copyTxt = function(text, fn) { // 複製功能 if (typeof document.execCommand !== 'function') { console.log('複製失敗,請長按複製') return } var dom = document.createElement('textarea') dom.value = text dom.setAttribute('style', 'display: block;width: 1px;height: 1px;') document.body.appendChild(dom) dom.select() var result = document.execCommand('copy') document.body.removeChild(dom) if (result) { console.log('複製成功') typeof fn === 'function' && fn() return } if (typeof document.createRange !== 'function') { console.log('複製失敗,請長按複製') return } var range = document.createRange() var div = document.createElement('div') div.innerhtml = text div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;') document.body.appendChild(div) range.selectNode(div) var selection = window.getSelection() console.log(selection) if (selection.rangeCount > 0) { selection.removeAllRanges() } selection.addRange(range) document.execCommand('copy') typeof fn === 'function' && fn() console.log('複製成功') }
export const castArray = value => (Array.isArray(value) ? value : [value]) export const castArray = arr=> Object.prototype.toString.call(arr) === '[object Array]'
export const isEmpty = (arr) => !Array.isArray(arr) || arr.length === 0
/** * @param {Array} arr */ const clone = (arr) => arr.slice(0); // Or const clone = (arr) => [...arr]; // Or const clone = (arr) => Array.from(arr); // Or const clone = (arr) => arr.map((x) => x); // Or const clone = (arr) => JSON.parse(JSON.stringify(arr)); // Or const clone = (arr) => arr.concat([]);
/** * @param {Array} arr * @returns {Array} */ export const uniqueArray = (arr) => Array.from(new Set(arr)) // Or export const uniqueArray = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i) // Or export const uniqueArray = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), [])
export const isPC = function() { // 是否為PC端 let userAgentInfo = navigator.userAgent let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'] let flag = true for (let v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false break } } return flag }
export const isWx = () => { // 判斷是否為微信 var ua = window.navigator.userAgent.toLowerCase() if (ua.match(/MicroMessenger/i) === 'micromessenger') { return true } return false }
export const isDevice = function() { // 判斷是android還是ios還是web var ua = navigator.userAgent.toLowerCase() if (ua.match(/iPhonesOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') { // ios return 'iOS' } if (ua.match(/Android/i) === 'android') { return 'Android' } return 'Web' }
/*正則匹配*/ export const normalReg = (str, type) => { switch (type) { case 'phone': //手機號碼 return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str); case 'tel': //座機 return /^(0d{2,3}-d{7,8})(-d{1,4})?$/.test(str); case 'card': //身份證 return /(^d{15}$)|(^d{18}$)|(^d{17}(d|X|x)$)/.test(str); case 'pwd': //密碼以字母開頭,長度在6~18之間,只能包含字母、數位和下劃線 return /^[a-zA-Z]w{5,17}$/.test(str) case 'postal': //郵政編碼 return /[1-9]d{5}(?!d)/.test(str); case 'QQ': //QQ號 return /^[1-9][0-9]{4,9}$/.test(str); case 'email': //郵箱 return /^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$/.test(str); case 'money': //金額(小數點2位) return /^d*(?:.d{0,2})?$/.test(str); case 'URL': //網址 return /(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&:/~+#]*[w-@?^=%&/~+#])?/.test(str) case 'IP': //IP return /((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))/.test(str); case 'date': //日期時間 return /^(d{4})-(d{2})-(d{2}) (d{2})(?::d{2}|:(d{2}):(d{2}))$/.test(str) || /^(d{4})-(d{2})-(d{2})$/.test(str) case 'number': //數位 return /^[0-9]$/.test(str); case 'positiveInteger': //正整數 return /^[1-9]d*$/.test(str); case 'price': //價格 return /(^[1-9]d*(.d{1,2})?$)|(^0(.d{1,2})?$)/.test(str);//價格非0則去掉'?' case 'english': //英文 return /^[a-zA-Z]+$/.test(str); case 'chinese': //中文 return /^[u4E00-u9FA5]+$/.test(str); case 'lower': //小寫 return /^[a-z]+$/.test(str); case 'upper': //大寫 return /^[A-Z]+$/.test(str); case 'HTML': //HTML標記 return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str); default: return true; } }
export const trim = function(str, type) { type = type || 1 switch (type) { case 1: return str.replace(/s+/g, '') case 2: return str.replace(/(^s*)|(s*$)/g, '') case 3: return str.replace(/(^s*)/g, '') case 4: return str.replace(/(s*$)/g, '') default: return str } }
export const filterTag = function(str) { // 過濾html程式碼(把<>轉換) str = str.replace(/&/ig, '&') str = str.replace(/</ig, '<') str = str.replace(/>/ig, '>') str = str.replace(' ', ' ') return str }
export const random = function(min, max) { // 生成亂數範圍 if (arguments.length === 2) { return Math.floor(min + Math.random() * ((max + 1) - min)) } else { return null } }
export const imgLoadAll = function(arr, callback) { // 圖片載入 let arrImg = [] for (let i = 0; i < arr.length; i++) { let img = new Image() img.src = arr[i] img.onload = function() { arrImg.push(this) if (arrImg.length == arr.length) { callback && callback() } } } }
export const insertAtCursor = function(dom, val) { // 遊標所在位置插入字元 if (document.selection) { dom.focus() let sel = document.selection.createRange() sel.text = val sel.select() } else if (dom.selectionStart || dom.selectionStart == '0') { let startPos = dom.selectionStart let endPos = dom.selectionEnd let restoreTop = dom.scrollTop dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length) if (restoreTop > 0) { dom.scrollTop = restoreTop } dom.focus() dom.selectionStart = startPos + val.length dom.selectionEnd = startPos + val.length } else { dom.value += val dom.focus() } }
export const getBase64 = function(img) { //傳入圖片路徑,返回base64,使用getBase64(url).then(function(base64){},function(err){}); let getBase64Image = function(img, width, height) { //width、height呼叫時傳入具體畫素值,控制大小,不傳則預設影象大小 let canvas = document.createElement("canvas"); canvas.width = width ? width : img.width; canvas.height = height ? height : img.height; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); let dataURL = canvas.toDataURL(); return dataURL; } let image = new Image(); image.crossOrigin = ''; image.src = img; let deferred = $.Deferred(); if (img) { image.onload = function() { deferred.resolve(getBase64Image(image)); } return deferred.promise(); } }
export const downloadFile = (base64, fileName) => { let base64ToBlob = (code) => { let parts = code.split(';base64,'); let contentType = parts[0].split(':')[1]; let raw = window.atob(parts[1]); let rawLength = raw.length; let uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }; let aLink = document.createElement('a'); let blob = base64ToBlob(base64); //new Blob([content]); let evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, true); //initEvent不加後兩個引數在FF下會報錯 事件型別,是否冒泡,是否阻止瀏覽器的預設行為 aLink.download = fileName; aLink.href = URL.createObjectURL(blob); aLink.click(); }
export const webPBool = () => !![].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0
/* 當軟體鍵盤彈起會改變當前 window.innerHeight 監聽這個值變化 [downCb 當軟鍵盤彈起後,縮回的回撥,upCb 當軟鍵盤彈起的回撥] */ export function(downCb, upCb) { var clientHeight = window.innerHeight downCb = typeof downCb === 'function' ? downCb : function() {} upCb = typeof upCb === 'function' ? upCb : function() {} window.addEventListener('resize', () => { var height = window.innerHeight if (height === clientHeight) { downCb() } if (height < clientHeight) { upCb() } }) }
function omit(object, props=[]){ let res = {} Object.keys(object).forEach(key=>{ if(props.includes(key) === false){ res[key] = typeof object[key] === 'object' && object[key] !== null ? jsON.parse(jsON.stringify(object[key])) : object[key] } }) return res } // for example let data = { id: 1, title: '12345', name: '男'} omit(data, ['id']) // data ---> {title: 'xxx', name: '男'}
export function deepClone(source) { if (!source && typeof source !== 'object') { throw new Error('error arguments', 'deepClone') } const targetObj = source.constructor === Array ? [] : {} Object.keys(source).forEach(keys => { if (source[keys] && typeof source[keys] === 'object') { targetObj[keys] = deepClone(source[keys]) } else { targetObj[keys] = source[keys] } }) return targetObj }
export function debounce(func, wait, immediate) { let timeout, args, context, timestamp, result const later = function() { // 據上一次觸發時間間隔 const last = +new Date() - timestamp // 上次被包裝函數被呼叫時間間隔 last 小於設定時間間隔 wait if (last < wait && last > 0) { timeout = setTimeout(later, wait - last) } else { timeout = null // 如果設定為immediate===true,因為開始邊界已經呼叫過了此處無需呼叫 if (!immediate) { result = func.apply(context, args) if (!timeout) context = args = null } } } return function(...args) { context = this timestamp = +new Date() const callNow = immediate && !timeout // 如果延時不存在,重新設定延時 if (!timeout) timeout = setTimeout(later, wait) if (callNow) { result = func.apply(context, args) context = args = null } return result } }
/** * @param {Function} func 目標函數 * @param {Number} wait 延遲執行毫秒數 * @param {Number} type type 1 表時間戳版,2 表定時器版 */ export function(func, wait ,type) { if(type===1){ let previous = 0; }else if(type===2){ let timeout; } return function() { let context = this; let args = arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }else if(type===2){ if (!timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } } }
到此這篇關於JavaScript常用的工具函數分享的文章就介紹到這了,更多相關JavaScript 工具函數內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45