Complete list of JavaScript native methods
1.Copy to clipboard
// 1.封装方法
function copyToClipboard(textToCopy) {
// navigator clipboard 需要https等安全上下文
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard 向剪贴板写文本
return navigator.clipboard.writeText(textToCopy);
} else {
// 创建text area
let textArea = document.createElement("textarea");
textArea.value = textToCopy;
// 使text area不在viewport,同时设置不可见
textArea.style.position = "absolute";
textArea.style.opacity = 0;
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
// 执行复制命令并移除文本框
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
}
// 2.页面上使用
var btn = document.getElementById("button");
btn.onclick =function(){
alert("你点击了按钮哦!");
copyToClipboard('我是复制的内容');
};
2. Get URL link parameters
// 1.封装方法, name为参数名称
getQueryString(name){
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const search = window.location.search.split('?')[1] || '';
const r = search.match(reg) || [];
return r[2];
}
// 2.页面上使用
let code = getQueryString('code');
3. Timestamp processing
// 1.封装方法
/**
* @param {Number} 时间标签 e.g. 1463368789
* @param {String} 格式 e.g. 'yyyy-MM-dd hh:mm'
* y 年,M 月,d 日,s 时,m 分,s 秒,w 星期,z 周, x 星期,q 季度,S 毫秒,
* @returns {String} e.g. '2016-05-16 11:19'
*/
function parseTime(time, formatter) {
let text = '';
if (arguments.length == 0) {
return ''
}
formatter = formatter || 'yyyy-MM-dd hh:mm:ss'
text = formatter.indexOf('z') != -1 ? '周' : formatter.indexOf('x') != -1 ? '星期' : '';
let date
if (typeof time === 'object') {
date = time
} else {
if (('' + time).length === 10) time = parseInt(time) * 1000
date = new Date(time)
}
const formatObj = {
'y': date.getFullYear(), // 年
'M': date.getMonth() + 1, // 月
'd': date.getDate(), // 日
'h': date.getHours(), // 时
'm': date.getMinutes(), // 分
's': date.getSeconds(), // 秒
'w': date.getDay(), // 星期
'q': Math.floor((date.getMonth() + 3) / 3), // 季度
'S': date.getMilliseconds() // 毫秒
}
return formatter.replace(/(y|M|d|h|m|s|w|z|x|q|S)+/g, kw => {
const key = kw.charAt(0)
let value = formatObj[key] || 0
if (key === 'w') return [text + '一', text + '二', text + '三', text + '四', text + '五', text + '六', text + '日'][value - 1]
if (key === 'x') return ''
if (key === 'z') return ''
const len = Math.min(kw.length, 4)
value = ('0000' + value).slice(-len)
return value
})
}
// 2.页面上使用
let code = parseTime(1463368789991);
4.Shuffle function
// 1.封装方法
// 原地洗牌算法
function shuffle(arr) {
for (let i = 0; i < arr.length; i++) {
let randomIndex = i + Math.floor(Math.random() * (arr.length - i))
;[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]]
}
return arr
}
// 非原地洗牌算法
function shuffle2(arr) {
let _arr = []
while(arr.length) {
let randomIndex = Math.floor(Math.random() * arr.length)
_arr.push(arr.splice(randomIndex, 1)[0])
}
return _arr
}
// 2.页面上使用
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8]))
console.log(shuffle2([1, 2, 3, 4, 5, 6, 7, 8]))
5. Deep copy
Deep copy implementation of objects and arrays For
simple objects or arrays, the more commonly used JSON.parse(JSON.stringify(obj))
following methods are suitable for deep copies of more complex objects or arrays.
// 1.封装方法
function deepClone(obj) {
if (!obj && typeof obj !== 'object') {
throw new Error('error arguments', 'shallowClone');
}
const newObj = obj.constructor === Array ? [] : {
};
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === 'object') {
newObj[key] = obj[key].constructor === Array ? [] : {
};
newObj[key] = deepClone(obj[key]);
} else {
newObj[key] = obj[key]
}
})
return newObj
}
// 2.页面上使用
console.log(deepClone([1, 2, 3, 4, 5, 6, 7, 8]))
6. Get random colors
Generate a color value of a random color, in the form of #ffffff
// 1.封装方法
function getRandomColor() {
const r = Math.round(Math.random() * 255);
const g = Math.round(Math.random() * 255);
const b = Math.round(Math.random() * 255);
const color = r << 16 | g << 8 | b;
return "#" + color.toString(16);
}
// 2.页面上使用
console.log(getRandomColor()) //#152368
7. Generate random code
Randomly generate a string of random codes, requiring some positions to be fixed numbers, and some positions to undergo some processing. for verification
// 1.封装方法
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0;
let v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// 2.页面上使用
console.log(guid())//154d0c01-a873-4db4-8c39-db3327352c89
Remarks :
(r & 0x3 | 0x8)
: Perform AND or calculation based on bits. For example,r=15
that is1111
;r & 0x3
that is0011
; that is, thatr & 0x3 | 0x8
is1011
11
v.toString(16)
: Convert numbers to characters in hexadecimal formatx
: The position is randomly replaced with a lettery
: The position is randomly replaced with a calculated letter, and the calculated value is10**
4
: The location will not be replaced, but the original one will be retained.4
8. Generate random strings
// 1.封装方法
// 生成随机的字母数字字符串
function getRandomStr(len) {
let str = ''
for (; str.length < len; str += Math.random().toString(36).substr(2));
return str.substr(0, len)
}
// 2.页面上使用
console.log(getRandomStr(10)); // e3bo5tj6ki
9. Obtain m unique random numbers in the range of n (m<n)
// 1.封装方法
function getRandomNumber(n, m) {
if (typeof n !== 'number' || typeof m !== 'number') {
throw Error('m和n必须是数字!');
}
if (m >= n) {
throw Error('m必须小于n!');
}
var arr = [],
result = [],
i = 0,
j = 0,
tempNumber = 0,
randomNumber = 0;
// 在两个数值间产生一个随机数
function selectFrom(lowerValue, upperValue) {
var choices = upperValue - lowerValue + 1;
return Math.floor(Math.random() * choices + lowerValue);
}
// 建一个n个元素的一维数组,放0 ~ n
for (; i < n; i++) {
arr[i] = i;
}
// 开始取 j ~ n-1 范内的随机数。把每次取到的随机数作为位置(数组的下标)与位置(数组的下标)为 j 的数交换数值
// 比如第一次去到32,将arr[32]和arr[0]互换,这样arr数组的1~n-1位置就没有32这个数了;然后再从1~n-1之间取随机数,以此类推
for (; j < m; j++) {
randomNumber = selectFrom(j, n - 1);
tempNumber = arr[j];
arr[j] = arr[randomNumber];
arr[randomNumber] = tempNumber;
result.push(arr[j]);
}
return result;
}
// 2.页面上使用
console.log(getRandomNumber(10, 5)); // [0, 4, 2, 1, 7]
10. Get the maximum value and minimum value in a pure numeric array
// 1.封装方法
//获取纯数字数组中最大值
function getMax(arr) {
return Math.max.apply(Math, arr);
}
//获取纯数字数组中最小值
function getMin(arr) {
return Math.min.apply(Math, arr);
}
// 2.页面上使用
const numbers = [5, 0, 120, -215, 228, 11233205, -75411]
console.log(getMax(numbers)); // 11233205
console.log(getMin(numbers)); // -75411