简单页面注入分析测试
//注入jquery便于解析操作DOM元素
var jqueryEle= document.createElement("script");
jqueryEle.src = "http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js";
document.body.appendChild(jqueryEle);
//注入moment便于解析操作日期
var momentEle=document.createElement("script");
momentEle.src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js";
document.body.appendChild(momentEle);
可用于浏览器开发者模式console标签注入使用
适合爬虫分析页面结构及测试
清除开发者模式console
console.clear();
js批量随机数生成
/**
* Created by Febby315 on 2017/6/30.
*/
//便于生成随机数组
function randomNumberArray(exp){
let reg=/(\(|\[)(-?[0-9]+(\.[0-9]+)?),(-?[0-9]+(\.[0-9]+)?)(\)|\])(\.([0-9]+))?(\*([0-9]+))?/gm.exec(exp);
if(reg){
let lb=reg[1]==="[", rb=reg[6]==="]";//lb左括号,rb右括号 ():false []:true 包含临界值
let dec=parseInt(reg[8])||0, num=parseInt(reg[10])||1;//dec小数位数,num组数
let min=parseFloat(reg[2])||0, max=parseFloat(reg[4])||1;//min最小值,max最大值
if(min<max){
let array = [],w = max-min;//返回的数组,最小值与最大值的差值
for(let i=num;i>0;i--){
let rn=min+Math.random()*w;
if(lb&&rb) rn=Math.round(rn*Math.pow(10,dec))/Math.pow(10,dec); //四舍五入 []
if(lb&&!rb) rn=Math.floor(rn*Math.pow(10,dec))/Math.pow(10,dec); //向下取整 [)
if(!lb&&!rb) rn=Math.floor(rn*Math.pow(10,dec))/Math.pow(10,dec); //向下取整 ()
if(!lb&&rb) rn=Math.ceil(rn*Math.pow(10,dec))/Math.pow(10,dec); //向上取整 (]
if(!lb&&!rb&&rn===min) { i++; continue; } //去除min重新获取()
array.push(rn);
}
return num!==1?array:array[0];
} else { return "参数有误" }
} else { return str+"\t表达式有误"; }
}
//测试用例
let str="(-10000.125,10000.125].4*10000000";
console.time("randomNumberArray");
console.log(randomNumberArray(str));
console.timeEnd("randomNumberArray");
console.log(JSON.stringify(randomNumberArray("[250,350].2*6")).replace(/,/gm,"\t"));
格式说明 (最小值,最大值).浮点精度*生成数量
小括号"()"为不包含最小值或最大值,中括号"[]"为包含最小值或最大值
解码html
//解码html
function decodeHtml(_str){
var _tab={"lt":"<","gt":">","nbsp":" ","amp":"&","quot":"\"","apos":"'"};
_str = _str.replace(/&[A-z\d]+;/g, function(_name){
return _tab[_name.slice(1,-1)]||_name;
});
_str = _str.replace(/&#[\d]+;/g, function(_dec){
return String.fromCharCode(_dec.slice(2,-1))||_dec;
});
_str = _str.replace(/&#x[A-F\d]{2,4};/g, function(_hex){
return String.fromCharCode('0x'+_hex.slice(3,-1))||_hex;
});
return _str;
}
//测试用例
console.time("decodeHtml");
console.log(decodeHtml("<p>HTML & 解码</p>"));
console.timeEnd("decodeHtml");
数组的一些常用操作
// 数组去重
Array.prototype.toHasArray = function(){
var hasList = [];
this.map(function(v){ hasList.indexOf(v) < 0 ? hasList.push(v) : null; });
return hasList;
};
//对象数组转键值对
Array.prototype.toMap=function(k){
var map={};
this.map(function(v){ v[k] ? map[v[k]]=v : console.error("This object has no %s property",k); });
return map;
};
//对象数组获取属性数组
Array.prototype.getPropToArray=function(k){
var arr=[];
this.map(function(v){ arr.push(v[k]); });
return arr;
};
//返回数组的最大值/最小值
Array.prototype.max = function (array) {
return Math.max.apply(Math, array ? array : this);
};
Array.prototype.min = function (array) {
return Math.min.apply(Math, array ? array : this);
};
//两个集合的差集 在arr不存在
Array.prototype.minus = function (arr) {
var result = new Array();
var obj = {};
for (var i = 0; i < arr.length; i++) {
obj[arr[i]] = 1;
}
for (var j = 0; j < this.length; j++) {
if (!obj[this[j]])
{
obj[this[j]] = 1;
result.push(this[j]);
}
}
return result;
};
建议了解一下lodash库有很多方便的函数
随机十六进制色值及rgb与hex色值互转
//随机生成十六进制颜色机生成十六进制颜色
function randomHexColor() {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6);
}
/**
* 颜色转化工具 By Febby315
*/
// "rgba(255,255,255,0)".rgbaToHex() -> #fff0
// "rgb(255,255,255)".rgbaToHex() -> #fff
String.prototype.rgbaToHex =function(){
var that = this.replace(/\s/g,"");
var rgba = that.match(/^rgb\(((\d+\,){2}\d+)\)$/i) || that.match(/^rgba\(((\d+\,){3}\d+)\)$/i); // rgb(255,255,255) || rgba(255,255,255,0)
if(that && rgba){
var re = rgba[1].split(",");
re.map(function(v,i,c){ c[i]=parseInt(v).toString(16).toUpperCase(); });
return "#"+re.join("");
}else{
return null;
}
}
// "#fff".hexToRgba()/"#f0f0f0".hexToRgba() -> rgb(255,255,255)
// "#f0f8".hexToRgba()/"#ff00ff78".hexToRgba() -> rgba(255,255,255,0)
String.prototype.hexToRgba =function(){
var that = this.replace(/\s/g,"");
var p = that.match(/^#(([0-9A-f]){3,4})$/) || that.match(/^#(([0-9A-f]{2}){3,4})$/); // 单值 #fff/#fff0 || 双值 #ffffff/#ffffff00
if(p){
var hex = [3,4].indexOf(hex.length)!=-1 ? p[1].replace(/([0-9A-z])/g,"$1$1") : p[1];
var re = hex.match(/.{2}/g);
re.map(function(v,i,c){ c[i]=parseInt(v,16); });
return re.length==3 ? "rgb("+ re.join(",") +")" : "rgba("+ re.join(",") +")";
}else{
return null;
}
}
对象深拷贝
//对象深拷贝
function clone(obj){
return typeof obj!="object"?obj:obj instanceof Date?new Date(obj):
obj instanceof Array?obj.map(function(val){ return clone(val); }):
obj instanceof Object?function(newObj){
Object.keys(this).map(function(v){ newObj[v]=clone(this[v]); }.bind(this));
return newObj;
}.bind(obj)({}):null;
}
//测试用例
var obj1={ a:12, b:"Febby", c:new Date(), d:[1,2,3], e:{ e1:"e1", e2:"e2" } };
var obj2=clone(obj1);
function testClone(o1,o2){
if(typeof o1==typeof o2&&typeof o1=="object"){
console.log("o1==o2",o1==o2);
for(let k in o1){
o1.hasOwnProperty(k)?testClone(o1[k],o2[k]):null;
}
}else{ console.error("类型不同或不属于对象类型",o1,o2); }
}
testClone(obj1,obj2);
对象转数组
// 对象转数组
const obj2Array = (_obj, _keys) => {
const keys = Array.isArray(_keys) ? _keys : Object.keys(_obj);
return keys.map(v => _obj[v]);
}
// 示例
const obj = { time: '2017-1-1', device: 200, sum: 300, remark: '说明备注' };
console.log('一个参数', obj2Array(obj));
console.log('两个参数', obj2Array(obj, ['time', 'device', 'sum']));
console.log('指定顺序', obj2Array(obj, ['device', 'time', 'sum']));
const list = [
{ time: '2017-1-1', device: 200, sum: 300 },
{ time: '2018-1-1', device: 300, sum: 400 },
];
console.log('数组类型', list.map(v => obj2Array(v)));
网友评论