主要收集一些项目中常见的js函数,更多请查看,现阶段收集较少,持续更新中 主要收集内容:
数组
清除数组中空元素
/**
* @param {Array} actual
* @returns {Array}
*/
function cleanArray(actual) {
const newArray = []
for (let i = 0; i < actual.length; i++) {
if (actual[i]) {
if(typeof(actual[i]) === "object") {
if(Object.keys(actual[i]).length !== 0){
newArray.push(actual[i])
}
} else {
newArray.push(actual[i])
}
}
}
return newArray
}
cleanArray(['a', '', 'b', '', 'c']) // ["a", "b", "c"]
是否数组
/**
* @param {Array} arg
* @returns {Boolean}
*/
function isArray(arg) {
if (typeof Array.isArray === 'undefined') {
return Object.prototype.toString.call(arg) === '[object Array]'
}
return Array.isArray(arg)
}
isArray([1,2,{a:2}]) // true
数组去重
普通数组
/**
* @param {Array} arr
* @returns {Array}
*/
function uniqueArr(arr) {
return Array.from(new Set(arr))
}
uniqueArr([1,4,2,2,2]) // [1, 4, 2]
对象数组
/**
* @param {Array} arr
* @returns {Array}
*/
function uniqueArr(arr) {
const keyArr = [];
arr.forEach((element,index) => {
keyArr.push(element.key); // 通过key来判断
});
const newArr = [];
const newKey = new Set(keyArr); // key去重
newKey.forEach(item =>{
const index = keyArr.findIndex(item2 => item2 === item);
newArr.push(arr[index]);
})
return newArr
}
const arr = [{
name: 'tom',
age: 12,
key: 1,
},
{
name: 'jurry',
age: 10,
key: 2,
},
{
name: 'jurry',
age: 10,
key: 2,
},
{
name: 'tom',
age: 12,
key: 1,
}];
uniqueArr(arr) // [{name: "tom", age: 12, key: 1},{name: "jurry", age: 10, key: 2}]
/**
* @param {Array} arr
* @returns {Array}
*/
function uniqueArr(arr){
const hash = {};
const newArray = arr.reduce((item, next)=>{
hash[next.key] ? '' : hash[next.key] = true && item.push(next);
return item;
},[])
return newArray
}
uniqueArr(arr) // [{name: "tom", age: 12, key: 1},{name: "jurry", age: 10, key: 2}]
数组去空
/**
* @param {Array} arr
* @returns {String}
*/
function ArrRemoveEmpty(arr){
return arr.filter(a => {
if((a !== '' && a !== null) || a !== undefined)
return a
})
}
ArrRemoveEmpty([1,2,,,3]) // [1, 2, 3]
数组转字符串
/**
* @param {Array} arr
* @param {String} l // 拼接符
* @returns {String}
*/
function ArrToStr(arr, l){
return arr.join(ls)
}
ArrToStr([1,2,3], ',') // 1,2,3
字符串
是否纯字母
/**
* @param {string} str
* @returns {Boolean}
*/
function validAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}
validAlphabets('helloworld') // true
validAlphabets('helloword111') // false
是否大写
/**
* @param {string} str
* @returns {Boolean}
*/
function validUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
validLowerCase('HELLOWORLD') // true
validLowerCase('HelloWorld') // false
是否小写
/**
* @param {string} str
* @returns {Boolean}
*/
function validLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}
validLowerCase('helloworld') // true
validLowerCase('HelloWorld') // false
是否字符串
/**
* @param {string} str
* @returns {Boolean}
*/
function isString(str) {
if (typeof str === 'string' || str instanceof String) {
return true
}
return false
}
isString('string') // true
字符长度
/**
* @param {string} input value
* @returns {number} output value
*/
function byteLength(str) {
// returns the byte length of an utf8 string
let s = str.length
for (var i = str.length - 1; i >= 0; i--) {
const code = str.charCodeAt(i)
if (code > 0x7f && code <= 0x7ff) s++
else if (code > 0x7ff && code <= 0xffff) s += 2
if (code >= 0xDC00 && code <= 0xDFFF) i--
}
return s
}
byteLength('中文') // 6
byteLength('string') // 6
字符串转数组
/**
* @param {string} string
* @returns {strgin} s // 分隔符
*/
function StrToArr(string, s) {
return string.split(s)
}
StrToArr('1,2,3', ',') // [1,2,3]
时间处理
日期格式化
/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string}
*/
function parseTime(time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'undefined' || time === null || time === 'null') {
return ''
} else 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(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
parseTime(new Date()) // "2021-03-19 15:35:55"
parseTime(new Date(), '{y}-{m}-{d} 周{a}') // "2021-03-19 周五"
时间戳计算
/**
* @param {number} time
* @param {string} option
* @returns {string}
*/
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() +
'分'
)
}
}
formatTime((new Date()).getTime() - 100000) //"2分钟前"
数据
银行卡号格式化
// 银行卡四位空格 格式化卡号显示,每4位加空格
formatCardNumber (e) {
// 获取input的dom对象
const input = e.target
// 获取当前光标的位置
const cursorIndex = input.selectionStart
// 字符串中光标之前空格的个数
const lineNumOfCursorLeft = (e.target.value.slice(0, cursorIndex).match(/\s/g) || []).length
// 去掉所有空格的字符串
const noLine = e.target.value.replace(/\s/g, '')
// 去除格式不对的字符并重新插入空格的字符串
const newCardNum = noLine.replace(/\D+/g, '').replace(/(\d{4})/g, '$1 ').replace(/\s$/, '')
// 改后字符串中原光标之前空格的个数
const newLineNumOfCursorLeft = (newCardNum.slice(0, cursorIndex).match(/\s/g) || []).length
// 光标在改后字符串中应在的位置
const newCursorIndex = cursorIndex + newLineNumOfCursorLeft - lineNumOfCursorLeft
// 赋新值,nextTick保证空格不能手动输入或删除,只能按照规则自动填入
this.$nextTick(() => {
this.entity.bankCardNumber = newCardNum
// 修正光标位置,nextTick保证在渲染新值后定位光标
this.$nextTick(() => {
// selectionStart、selectionEnd分别代表选择一段文本时的开头和结尾位置
input.selectionStart = newCursorIndex
input.selectionEnd = newCursorIndex
})
})
}
邮箱
是否邮箱
/**
* @param {string} email
* @returns {Boolean}
*/
function validEmail(email) {
const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return reg.test(email)
}
validEmail('1324841836@qq.com') // true
替换邮箱字符
/**
* @param {string} email
* @returns {string}
*/
function regEmail(email) {
if (String(email).indexOf('@') > 0) {
const str = email.split('@')
let _s = ''
if (str[0].length > 3) {
for (var i = 0; i < str[0].length - 3; i++) {
_s += '*'
}
}
var new_email = str[0].substr(0, 3) + _s + '@' + str[1]
}
return new_email
}
regEmail('1324841836@qq.com') // "132*******@qq.com"
html
创建div标签
/**
* @param {string} val
* @returns {string}
*/
function html2Text(val) {
const div = document.createElement('div')
div.innerHTML = val
return div.textContent || div.innerText
}
class
判断class是否存在
/**
* Check if an element has a class
* @param {HTMLElement} elm
* @param {string} cls
* @returns {boolean}
*/
function hasClass(ele, cls) {
return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}
添加class
/**
* Add class to element
* @param {HTMLElement} elm
* @param {string} cls
*/
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += ' ' + cls
}
移除class
/**
* Remove class from element
* @param {HTMLElement} elm
* @param {string} cls
*/
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
ele.className = ele.className.replace(reg, ' ')
}
}
http
判断合法url
function validURL(url) {
const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return reg.test(url)
}
validURL('https://github.com/search?o=desc&p=2&q=vuepress&s=stars&type=Repositories') // true
判断合法IP
/**
* 是否合法IP地址
* @param value
*/
function validateIP(value) {
if (value === '' || value === undefined || value == null) {
return false
} else {
const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
if ((!reg.test(value)) && value !== '') {
return false
} else {
return true
}
}
}
validateIP('128.96.103.126') // true
对象
对象合并
/**
* Merges two objects, giving the last one precedence
* @param {Object} target
* @param {(Object|Array)} source
* @returns {Object}
*/
function objectMerge(target, source) {
if (typeof target !== 'object') {
target = {}
}
if (Array.isArray(source)) {
return source.slice()
}
Object.keys(source).forEach(property => {
const sourceProperty = source[property]
if (typeof sourceProperty === 'object') {
target[property] = objectMerge(target[property], sourceProperty)
} else {
target[property] = sourceProperty
}
})
return target
}
objectMerge({a:1},{c:3,f:4}) // {a: 1, c: 3, f: 4}
深度克隆
/**
* This is just a simple version of deep copy
* Has a lot of edge cases bug
* If you want to use a perfect deep copy, use lodash's _.cloneDeep
* @param {Object} source
* @returns {Object}
*/
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
}
deepClone({a:3}) // {a: 3}
更多请查看