JS常用方法总结

1、滚动到页面顶部
const scrollToTop = () => {
	const c = document.documentElement.scrollTop || document.body.scrollTop;
	if (c > 0) {
		// requestAnimationFrame:执行向上滚动动画
		window.requestAnimationFrame(scrollToTop);
		window.scrollTo(0, c - c / 8);
	}
}

scrollToTop();
2、元素节点是否在可视区域内
const inViewport = (el, partiallyVisible = false) => {
	// 返回元素的大小及其相对于视口的位置
	const { top, left, bottom, right } = el.getBoundingClientRect();
	const { innerHeight, innerWidth } = window;
	return partiallyVisible
		? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
		 	((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
		: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// 左右可见
inViewport(node); 
// 全屏(上下左右)可以见
inViewport(node, true); 
3、抽取url中参数
/**
 * 1、match(searchvalue/regexp)
 * 	a、检索string,返回index等
 *  b、匹配正则,
 * 		在进行正则匹配时,若添加了全局g,那么会进行全局检索,若没有则会匹配一次
 * 2、array.reduce(function(pre, cur, inx, arr){}, initialValue)
 * 	  累加器,	根据某个规则把数组组合成对象
*/
const urlLParams = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );
const p1 = urlLParams('https://blog.csdn.net/jiuwanli666?article=166&name=888');
 const p2 = urlLParams('https://blog.csdn.net/jiuwanli666');
4、毫秒数 => 可读时间
const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
	const timeStr = {
		day: '天',
		hour: '小时',
		minute: '分钟',
		second: '秒',
		millisecond: '毫秒'
	}
	/**
	 * 1、Object.entries(String/Array/Object)
	 * 	返回一个迭代数组(多维数组)
	 * 	子元素是数组,孙元素分别是key/index和value
	 * 	eg:
	 * 		Object.entries('ti')  => [['0', 't'], ['1', 'i']]
	 * 		Object.entries([1,2]) => [['0', 1], ['1', 2]]
	 * 		Object.entries({name: '清雅', gender: 0}) => [['name', '清雅'], ['gender', 0]]
	 * 2、Array方法
	 * 	a、filter,创建一个符合条件的新数组
	 * 		且不会对就数组进行更改
	 * 		eg: [1,2].filter(val => val > 1) => [2]
	 * 	b、map,数组遍历,组成一个新数组
	 * 		 
	*/
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${timeStr[key]}`)
    .join('- ');
};
formatDuration(new Date().getTime())
// 18347 天- 3 小时- 39 分钟- 56 秒- 248 毫秒
5、复制文本信息
/**
 * 思路:
 * 		创建一个只读的文本域
 *
 * 1、getSelection
 * 		表示用户选择的文本范围或者光标的当前位置
 * 2、execCommand
 * 		允许运行命令来操纵可编辑区域的元素
 */
const copyToClipboard = str => {
	 const el = document.createElement('textarea');
	 el.value = str;
	 el.setAttribute('readonly', '');
	 el.style.position = 'absolute';
	 el.style.left = '-9999px';
	 document.body.appendChild(el);
	 const selected =
	 	document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
	 el.select();
	 document.execCommand('copy');
	 document.body.removeChild(el);
	 if (selected) {
		 document.getSelection().removeAllRanges();
		 document.getSelection().addRange(selected);
	 }
};
6、计数器
const counter = (selector, start, end, step = 1, duration = 2000) => {
	let current = start,
		_step = (end - start) * step < 0 ? -step : step,
		timer = setInterval(() => {
			current += _step;
			document.querySelector(selector).innerHTML = current;
			if (current >= end) clearInterval(timer);
		}, Math.abs(Math.floor(duration / (end - start))));
	return timer;
};
// 事例
counter('.box', 1, 1000, 5, 2000); 
7、生成uuid
/**
 * 生成uuid
 * @param {number} len 生成指定长度的uuid
 * @param {number} radix uuid进制数
 */
export function uuid(len, radix) {
    let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    let uuid = [], i;
    radix = radix || chars.length;
 
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      let r;
 
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
 
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
 
    return uuid.join('');
}
8、颜色转换16进制转rgba
/**
 * @param {String} hex
 * @param {Number} opacity
 */
export function hex2Rgba(hex, opacity) {
	if(!hex) hex = "#2c4dae";
    return "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt("0x" + hex.slice(5, 7)) + "," + (opacity || "1") + ")";
}
9、去除html标签
const htmlSafeStr = (str) => {
    return str.replace(/<[^>]+>/g, "")
}
10、控制字符串显示,超出指定字数则显示省略号
const getSubStringSum = (str = "", num = 1) => {
    let newStr;
    if(str){
        str = str + '';
        if (str.trim().length > num ) {
            newStr = str.trim().substring(0, num) + "...";
        } else {
            newStr = str.trim();
        }
    }else{
        newStr = ''
    }
    return newStr;
}
11、数组排序(一)
// 上移、下移、置顶、置底
<el-button type="text" style="color: rgb(207, 0, 14)" @click="moduleMove('Up', scope.$index)">上移</el-button>

/**
 * 模块排序
 * @param {String} status 模块排序方式 
 * @param {Number} index 当前位置 
*/
swapArray: function (arr, index1, index2) {
	arr[index1] = arr.splice(index2, 1, arr[index1])[0]
	return arr
},
moduleMove: function (status, index) {
	const { tableData, tableDataTotal } = this
	this[`to${status}`](tableData, index, tableData.length)
},
toDown: function (arr, index, length){
	if(index + 1 != length){
		this.swapArray(arr, index, index + 1)
		return
	}
	alert('已经置底,无法下移!')
},
toUp: function (arr, index, length){
	if(index != 0){
		this.swapArray(arr, index, index-1)
		return
	}
	alert('已经置顶,无法上移')
},
toBottom: function(arr, index, length){
	if(index + 1 != length){
		let moveNum = length - 1 - index
		for (let i = 0; i< moveNum; i++) {
			this.swapArray(arr, index, index + 1)
			index ++
		}
		return
	}
	alert('已经处于置底状态!')
},
toTop: function(arr, index, length){
	if(index != 0){
		//首先判断当前元素需要上移几个位置,置底移动到数组的第一位
		let moveNum = index - 0;
		//循环出需要一个一个上移的次数
		for (let i = 0; i< moveNum; i++) {
			this.swapArray(arr, index, index - 1)
			index --
		}
		return
	}
	alert('已经处于置顶状态!')
}
12、数组排序(二)
// 更换数组任意位置,常见情形:拖拽排序
const moveList = (arr, oldInx, newInx) => {
	let arr_temp = [].concat(arr)
	arr_temp.splice(newInx, 0, arr_temp.splice(oldInx, 1)[0])
	return arr_temp
}
13、简写属性
let fn = (x, y) => {
	return { x, y }
}
console.log(fn(1, 2)) // { x: 1, y: 2 } 
14、数组元素:对象去重
const tableDataAll = [{a:1,b:2}, {a:1,b:2}, {a:2}];
const arr = []
const obj = {}
arr = tableDataAll.reduce(function(item, next) {
// 针对属性a对数组去重
 obj[next.a] ? '' : obj[next.a] = true && item.push(next)
 return item
}, []);
15、文件阅读器(返回base64)
function readerfile(file) {
	return new Promise((resolve, reject) => {
		// 创建文件阅读器
		let reader = new FileReader();
		reader.addEventListener("load", function() {
			resolve(reader.result);
		}, false)
		if (file) {
			reader.readAsDataURL(file)
		}
	})
}
readerfile(file[0]).then(base64Str => {
	// base64
})
16、Blob、base64相互转换
// Blob转base64
function blobToDataURL(blob, callback) {
	let a = new FileReader();
	a.onload = function (e) { callback(e.target.result); }
	a.readAsDataURL(blob);
}
// 使用:
blobToDataURL(result, (base64)=>{})

// base64转Blob
base64转Blob
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
17、图片压缩
使用Compressor
https://github.com/fengyuanchen/compressorjs
let file = document.getElementById('file').files;
new Compressor(file[0], {
	quality: 0.6,
	success(result) {}
})
18、倒计时
countDown: function (nowtime, endtime) {
			let lefttime = endtime.getTime() - nowtime.getTime(),  //距离结束时间的毫秒数
					leftd = Math.floor(lefttime/(1000*60*60*24)),  //计算天数
					lefth = Math.floor(lefttime/(1000*60*60)%24),  //计算小时数
					leftm = Math.floor(lefttime/(1000*60)%60),  //计算分钟数
					lefts = Math.floor(lefttime/1000%60);  //计算秒数
			function addZero (str) {
				if (str < 10) {
					return '0' + str
				}
				return str
			}
			if (this.orderData.orderStatus == 1) { // 待付款
				return addZero(lefth) + "小时" + addZero(leftm) + "分"
			}
			return addZero(leftd) + "天" + addZero(lefth) + "小时" + addZero(leftm) + "分"
		}
19、根据文件路径生成文件信息
this.fileList.push({
	uid: new Date().getTime() + i,
   	name: '小文件',
    status: 'done',
    url: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2853553659,1775735885&fm=26&gp=0.jpg',
    size: 666666,
     fileType: ''
})
20、let ar_1 = [a,b],ar_2 = [1,2,3,6] ==> { a: [1,2], b: [3,6] }
const p = [a, b]
const ps = [1, 2, 3, 6]
const res = (p,ps) => {
		return p.reduce((cur, pre, index) => {
		if (!cur[pre]) {
			cur[pre] = []
		}
		for (let i = 0; i < ps.length; i++) {
			if (index === i) {
				cur[pre].push(ps[i])
			}
		}
		return cur
	}, {})
}
21、数组元素的某个key,对数组元素重新分组
const arr = [
	{name: '赵', age: 18, score: 60, weight: 60},
	{name: '王', age: 19, score: 70, weight: 55},
	{name: '李', age: 18, score: 60, weight: 70},
	{name: '刘', age: 20, score: 70, weight: 65},
	{name: '赵', age: 18, score: 60, weight: 60},
	{name: '钱', age: 19, score: 70, weight: 55},
]
const groupBy = (arr, key) => {
	return arr.reduce((pre,cur) => {
		pre[cur[key]] = pre[cur[key]] || []
		pre[cur[key]].push(cur)
		return pre
	}, {})
}
console.log(groupBy(arr, 'age'))
22、扁平化多维数组
const c = [[1,2,3],[4,5,[6,7]]]
const flatMap = (arr) => {
   return arr.reduce((pre,item) => {
      return pre.concat(Array.isArray(item) ? flatMap(item): item)
   },[])
}
23、字母大小写转换
const str = 'abCDef'
const change = (str) => {
   let arr = str.split('')
   return arr.reduce((pre,cur) => {
     if (cur === cur.toLowerCase()) {
       pre.push(cur.toUpperCase())
     } else {
       pre.push(cur.toLowerCase())
     }
     return pre
   },[])
 }
24、数组公共元素
const arr1 = [1,2,3,4]
const arr2 = [6,4,7,8,3]
const arr3 = [0,9,4,3]
const getOnly = (...arr) => {
  return arr.reduce((pre,next) => {
    return pre.filter(c => next.includes(c))
  },arr[0])
}
console.log(getOnly(arr10,arr2,arr3))
25、每个字符出现的次数
const str1 = 'jgdsgdlkgj'
const op = str1.split('').reduce((pre,next)=> {
  pre[next]? pre[next]++: pre[next]=1
  return pre
},{})
{j: 2, g: 3, d: 2, s: 1, l: 1}
26、查找公共前缀
const strArr = ["flowers","flow","flight"]
const getStr = (strs) => {
    return strs.reduce((pre,next) => {
        while (!next.startsWith(pre)) {
            pre = pre.substring(0,pre.length-1)
        }
        return pre
    },strs[0])
}
27、保存远程图片到本地
const downImg = imgUrl => {
	const image = new Image();
	const _this = this
	// 解决跨域 canvas 污染问题
	image.setAttribute("crossOrigin", "anonymous");
	image.onload = function() {
		const canvas = document.createElement("canvas");
		canvas.width = image.width;
		canvas.height = image.height;
		const context = canvas.getContext("2d");
		context.drawImage(image, 0, 0, image.width, image.height);
		//得到图片的base64编码数据
		const obj = imgUrl.split('?')[0].split('.')
		const url = canvas.toDataURL(`image/${obj[obj.length - 1]}`)
		const nameArr = imgUrl.split('?')[0].split('/')
		// 生成一个 a 标签
		const a = document.createElement("a");
		// 创建一个点击事件
		const event = new MouseEvent("click");
		// 将 a 的 download 属性设置为我们想要下载的图片的名称,若 name 不存在则使用'图片'作为默认名称
		a.download = nameArr[nameArr.length - 1] || "图片";
		// 将生成的 URL 设置为 a.href 属性
		a.href = url;
		// 触发 a 的点击事件
		a.dispatchEvent(event);
		_this.downInx = _this.downInx + 1
		if (_this.downInx == _this.downLoadList.length - 1) {
			_this.downInx = -1
		}
		// return a;
	};

	image.src = imgUrl + '?v=' + new Date().getTime()
}
28、两个变量值的交换
const a = { a: 1, c: 3 }, b = { b: 2 }
a = [b, b = a];
29、随机生成字符串
const fn = len => {
    var rdmString = "";
    for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
    return rdmString.substr(0, len);
}
30、滚动到页面顶部
window.scrollTo(0, 0)
31、交换两个变量值
let a = { a: 1 }
let b = { b: 2 }
[a, b] = [b, a]
32、计算两个日期天数
const daysDiff = (date, date2) => Math.ceil(Math.abs(date - date2) / 86400000)
console.log(daysDiff(new Date('2021-05-10'), new Date('2021-11-25')))
33、数据类型
const trueTypeOf = (obj) => {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function

版权声明:本文为jiuwanli666原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。