ps: 无框架时, 使用js的一些功能完成一些小demo
记录方法,方便自己查询
//追加replaceAll方法
String.prototype.replaceAll = function (s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2);
}
let strArr = strData.split("\n")
// 分割excel,split中的文本为excel特殊分隔符
const excelSplit = (v) => {
return v.split(` `)
}
// 去除所有空格
const removeSpaces = (str) => {
str = str.trim();
str = str.replace(/\s/g, "")
return str;
}
//追加constains方法
String.prototype.constains = function (v) {
return this.indexOf(v) === -1 ? false : true;
}
//追加constains方法 忽略大小写
String.prototype.constainsIgnoreCase = function (v) {
var a = this.toUpperCase();
var b = v.toUpperCase();
return a.indexOf(b) === -1 ? false : true;
}
/*获取多行注释内内容*/
Function.prototype.getMultiLine = function () {
var lines = new String(this);
lines = lines.substring(lines.indexOf("/*") + 3, lines.lastIndexOf("*/"));
return lines;
};
# foreach
arr.forEach(p => {
let point = p.getCoordinates()
s += `${point[0]} ${point[1]}\n`
})
# map
datas.map((item, key) => {
})
//两个数组中筛选不同值
function diff(arr1, arr2) {
var newArr = [];
var arr3 = [];
for (var i=0;i<arr1.length;i++) {
if(arr2.indexOf(arr1[i]) === -1)
arr3.push(arr1[i]);
}
var arr4 = [];
for (var j=0;j<arr2.length;j++) {
if(arr1.indexOf(arr2[j]) === -1)
arr4.push(arr2[j]);
}
newArr = arr3.concat(arr4);
return newArr;
}
const randomNum= function (Min, Max) {
var Range = Max - Min;
var Rand = Math.random();
return (Min + Math.round(Rand * Range));
}
//判断元素是否未定义
utils.isUndef = function (v) {
return v === undefined || v === null;
}
//判断元素是否定义
utils.isDef = function isDef(v) {
return v !== undefined && v !== null
}
//判断元素是否为true
utils.isTrue = function (v) {
return v === true
}
//判断元素是否为false
utils.isFalse = function (v) {
return v === false
}
// 转换toString
utils.toString = function (val) {
return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val)
}
//转换toNumber
utils.toNumber = function (val) {
var n = parseFloat(val);
return isNaN(n) ? val : n
}
const uuid = function () {
function formatDateTime() {
var date = new Date();
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
return y + m + d + h + minute + second;
}
var uuid = formatDateTime() + Math.random().toString(36).substr(2);
return uuid;
}
// 方式2
uuid: (simple = false) => {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
if (simple) {
return (S4() + S4() + S4())
} else {
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}
},
// 追加日期格式化
Date.prototype.format = function (format) {
/*
* eg:format="yyyy-MM-dd hh:mm:ss";
*/
var o = {
"M+": this.getMonth() + 1, // month
"d+": this.getDate(), // day
"h+": this.getHours(), // hour
"m+": this.getMinutes(), // minute
"s+": this.getSeconds(), // second
"q+": Math.floor((this.getMonth() + 3) / 3), // quarter
"S+": this.getMilliseconds()
// millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
- RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
var formatStr = "";
for (var i = 1; i <= RegExp.$1.length; i++) {
formatStr += "0";
}
var replaceStr = "";
if (RegExp.$1.length == 1) {
replaceStr = o[k];
} else {
formatStr = formatStr + o[k];
var index = ("" + o[k]).length;
formatStr = formatStr.substr(index);
replaceStr = formatStr;
}
format = format.replace(RegExp.$1, replaceStr);
}
}
return format;
}
// yyyy-mm-dd格式比较
compareTime: (startDate, endDate) => {
var date1 = strFormatDate(startDate)
var date2 = strFormatDate(endDate)
if (date1.getTime() > date2.getTime()) {
return false
} else {
return true
}
function strFormatDate(str) {
return new Date(Date.parse(str.replace(/-/g, '/')))
}
}
/**
*
* tree转数组
* @param {*} list
* @param {*} [newArr=[]]
* @returns {*}
*/
const treeToArray = (list, newArr = []) => {
list.forEach((item) => {
const { children } = item
if (children) {
newArr.push(item)
return treeToArray(children, newArr)
}
newArr.push(item)
})
return newArr
}
/**
* 获取tree 中key的父节点
* @param {*} key
* @param {*} tree
* @returns
*/
const getParentKey = (key, tree) => {
let parentKey
for (let i = 0; i < tree.length; i++) {
const node = tree[i]
if (node.children) {
if (node.children.some(item => item.key === key)) {
parentKey = node.key
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children)
}
}
}
return parentKey
}
/**
*
* 遍历查找key
* @param {*} data 数组
* @param {*} key key
* @param {*} callback 回调函数
*/
const loop = (data, key, callback) => {
data.forEach((item, index, arr) => {
if (item.key === key) {
return callback(item, index, arr)
}
if (item.children) {
return loop(item.children, key, callback)
}
})
}
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://192.168.101.10:9001/proxyHttp/getKkxx');
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
httpRequest.open('POST', 'url', true); //第二步:打开连接
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
httpRequest.send('name=teswe&ee=ef');//发送请求 将情头体写在send中
httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
var json = httpRequest.responseText;//获取到服务端返回的数据
console.log(json);
}
};
var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
httpRequest.open('POST', 'url', true); //第二步:打开连接/***发送json格式文件必须设置请求头 ;如下 - */
httpRequest.setRequestHeader("Content-type","application/json");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)var obj = { name: 'zhansgan', age: 18 };
httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中
httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
var json = httpRequest.responseText;//获取到服务端返回的数据
console.log(json);
}
};
# 写入到粘贴板
navigator.clipboard.writeText(text)
# 复制动作
const inputEle = document.querySelector("#input");
inputEle.select();
document.execCommand("copy");
function paste() {
navigator.clipboard // 创建clipboard对象
.readText() // 调用readText()方法
.then((clipText) => {
// 成功回调
console.log(clipText); // clipText是从剪贴板读取到的内容(也就是要粘贴的内容)
})
.catch((err) => console.log("粘贴失败!",err)); // 失败回调
}
const getUrlParam = function (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r !== null) {
return decodeURI(r[2]);
} else {
return r;
}
}
//TODO