记录错误日志
window.onerror = function(message, url, lineNumber,columnNo,error) {
var data = {
'message':message,
'url':url,
'error':error.stack
};
$.ajax({
url:"/error/capture",
type:'post',
data:data,
success:function(){
}
});
return true;
};
javascript随机数生成算法
function rnd( seed ){
seed = ( seed * 9301 + 49297 ) % 233280; //为何使用这三个数?
return seed / ( 233280.0 );
};
function rand(number){
today = new Date();
seed = today.getTime();
return Math.ceil( rnd( seed ) * number );
};
myNum=(rand(5));
var rand = (function(){
var seed = (new Date()).getTime()
function r(){
seed = (seed*9301+49297)%233280
return seed/(233280.0)
}
return function(number){
return Math.ceil(r()*number)
}
})()
rand = (function(){
var today = new Date();
var seed = today.getTime();
function rnd(){
seed = ( seed * 9301 + 49297 ) % 233280;
return seed / ( 233280.0 );
};
return function rand(number){
// return Math.ceil(rnd(seed) * number);
return Math.ceil(rnd() * number);
};
})();
myNum = (rand(5));
JavaScript 中,如何求出两个数组的交集和差集
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
let a = new Set([1, 2, 3]);
let b = new Set([3, 5, 2]);
// 并集
let unionSet = new Set([...a, ...b]);
//[1,2,3,5]
// 交集
let intersectionSet = new Set([...a].filter(x => b.has(x)));
// [2,3]
// ab差集
let differenceABSet = new Set([...a].filter(x => !b.has(x)));
// [1]
再把Set转换为数组即可.
let arr = Array.from(set);
// 或 let arr = [...set];
相同的
a.filter(function(v){ return b.indexOf(v) > -1 })
不同的
a.filter(function(v){ return !(b.indexOf(v) > -1) }).concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}))
获取某个DOM元素绑定的事件
getEventListeners($('selector')) 方法以数组对象的格式返回某个元素绑定的所有事件
getEventListeners($('#firstName')).click[0].listener 会返回ID为 firstName 元素绑定的click事件
inspect($('selector')) 会检查所有匹配选择器的DOM元素,并返回所有选择器选择的DOM对象。例如inspect($('#firstName')) 选择所有ID是 firstName 的元素,inspect($('a')[3]) 检查并返回页面上第四个 p元素。
$0, $1, $2等等会返回你最近检查过的几个元素,例如 $0 会返回你最后检查的元素,$1 则返回倒数第二个
img onerror事件触发
$('img').each(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
this.src = 'default.png';
}
});
禁止浏览器记住密码
在input[type=’password’]的前面加上一个隐藏的密码框即可,且要求是:不能添加id和name属性
<input type='password' style='display:none;' />
通过 js 修改微信浏览器的title
var $body = $('body');
document.title = ‘title’
// hack在微信等webview中无法修改document.title的情况
var $iframe = $('<iframe src="/favicon.ico"></iframe>').on('load', function() {
setTimeout(function() {
$iframe.off('load').remove()
}, 0)
}).appendTo($body)
图片的预加载
function imgLoad(src){
var img = new Image();
if(img.complete){ //从缓存里面取
callback();
}else{
img.onload = function(){ //实际加载完成
callback();
}
}
img.src = src;
}
实现类似于add(1)(2)(3)调用
function add(x){
var sum = x;
var tmp = function(y){
sum = sum + y;
return tmp;
}
tmp.toString = function(){
return sum;
}
return tmp
}
用代码来画个国旗
<html>
<head>
<script>
var col=new Array("red","brown");
var ticker=0;
var step=0;
function drawBackground(){
var g=document.getElementById("background").getContext("2d");
var grd=g.createLinearGradient(-560+ticker, 0, 1400+ticker,0);
for (var i=0; i<10; i++)
grd.addColorStop(i/10,col[(i + step)%col.length]);
ticker=ticker+10;
if (ticker>=196){
ticker=0;
step++;
}
g.fillStyle=grd;
g.fillRect(0,0,1600,700);
}
function preperation(){
setInterval('drawBackground()',100);
}
</script>
<style type="text/css">
#myCanvas{
z-index:2;
position:absolute; left:0px; top:-5px;
}
#background{
z-index:1;
position:absolute;
left:0px;
top:0px;
}
</style>
</head>
<body onLoad="preperation()">
<canvas id="myCanvas" width="900" height="600" >
Your browser does not support the HTML5 canvas tag.
</canvas>
<canvas id="background" width="1600" height="700" ></canvas>
<script>
var x=new Array(0,12,54,18,28,0,-28,-18,-54,-12,0); //五角星样品坐标xx数组
var y=new Array(-53,-17,-17,1,45,19,45,1,-17,-17,-53); //五角星样品坐标y数组
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d"); //获得画笔
//样品数组x轴坐标 a , 和y轴坐标 b
//指定位置[locationX,locationY]
//真实五角星的大小,与样品五角星尺寸之比 f
//五角星画完后,旋转的角度 rotation
function star(a,b,locationX,locationY,f,rotation){
ctx.save();//记录画图(画笔)的初始环境
ctx.translate(locationX,locationY);
ctx.rotate(rotation*Math.PI/180.0);
ctx.beginPath();
ctx.moveTo(Math.round(a[0]*f),Math.round(b[0]*f));
for (var i=1;i<a.length;i++)
ctx.lineTo(Math.round(a[i]*f),Math.round(b[i]*f));
ctx.closePath();
ctx.fillStyle="yellow";
ctx.fill();
ctx.restore();//还原画图(画笔)的初始环境
}
star(x,y,165,165,1.4,0);//画大五角星
star(x,y,301,65,0.5,30);//画小五角星
star(x,y,362,126,0.5,-30);//画小五角星
star(x,y,359,216,0.5,0);//画小五角星
star(x,y,301,273,0.5,30);//画小五角星
</script>
</body>
</html>
js获取URL中的参数
function getQueryString(url, name) {
var reg = new RegExp("(^|&|\\?)" + name + "=([^&]*)(&|$)", "i");
var r = url.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
视频video标签在移动端的播放总结
function video_loading( $video ){
$('.video_loading').show();
var timer = setInterval(function(){
var currentTime = $video[0].currentTime; // 检测当前的播放时间
if( currentTime>0 ){
$('.video_loading').hide();
clearInterval( timer );
}
}, 100)
}
/**
视频的播放时间改变时进行的操作
videoid video标签的id
cur 当前播放时间,可以传入ended参数
func 回调函数
*/
videoUpdate : function(videoid, cur, func){
var myVideo = document.getElementById(videoid);
if( myVideo ){
if( typeof cur =='number' ){
myVideo.addEventListener('timeupdate', function(){
if( this.currentTime>=cur ){
func();
myVideo.removeEventListener('timeupdate', function(){
}, false);
}
}, false);
}else{
myVideo.addEventListener(cur, function(){
func();
}, false);
}
}
}
// 第一屏的视频进行到4秒时,显示透明图层以提供用户操作
tool.videoUpdate( 'video1', 4, function(){
$('.s1 .overlay').show();
});
// 第一屏的视频结束时,显示向下滑动提示按钮
tool.videoUpdate( 'video1', 'ended', function(){
$('.s1 .tip').show();
});
为博客的文章添加二维码
$('.bcontent').append('<div class="qrcode"><a href="javascript:;">点击生成二维码,可在手机端观看</a><div class="tsp"></div></div>');
$('.bcontent').on('click', '.qrcode a', function(){
var $tsp = $(this).next();
if( $tsp.find('canvas').length ){
if( $tsp.css('display')=='block' ){
$tsp.hide();
}else{
$tsp.show();
}
}else{
if( self.showing ){
return;
}
self.showing = true;
$tsp.show().html( '正在生成中...' );
$.ajax({
url : 'jquery.qrcode.min.js',
dataType : 'script',
type : 'get'
}).done(function(){
self.showing = false;
$tsp.html('');
$tsp.qrcode({
render : 'canvas',
width : 176,
height: 176,
text : window.location.href
});
})
}
})
使用DOM中的a标签解析url
// 创建一个额外的a标签
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}
var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
myURL.file; // 'index.html'
myURL.hash; // 'top'
myURL.host; // 'abc.com'
myURL.query; // '?id=255&m=hello'
myURL.params; // Object = { id: 255, m: hello }
myURL.path; // '/dir/index.html'
myURL.segments; // Array = ['dir', 'index.html']
myURL.port; // '8080'
myURL.protocol; // 'http'
myURL.source; // 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
javascript如何添加前置0
function addPreZero(num){
return ('000000000'+num).slice(-10);
}
html5实现图片预览和查看原图
<input type="file" id='upimg' />
var upimg = document.querySelector('#upimg');
upimg.addEventListener('change', function(e){
var files = this.files;
if(files.length){
// 对文件进行处理,下面会讲解checkFile()会做什么
checkFile(this.files);
}
});
// 图片处理
function checkFile(files){
var file = files[0];
var reader = new FileReader();
// show表示<div id='show'></div>,用来展示图片预览的
if(!/image\/\w+/.test(file.type)){
show.innerHTML = "请确保文件为图像类型";
return false;
}
// onload是异步操作
reader.onload = function(e){
show.innerHTML = '<img src="'+e.target.result+'" alt="img">';
}
reader.readAsDataURL(file);
}
移动端在页面输出调试信息
function log(){
try{
throw new Error();
}catch(e){
console.log(e.stack);
}
}
log();
function log(msg){
var $body = document.querySelector('body');
if( !$body.querySelector('.info_wz_852') ){
$body.innerHTML += '<div class="info_wz_852" style="position:fixed;top:0;left:0;z-index:99999; background:#000;color:#f00;"></div>';
}
var $info = $body.querySelector('.info_wz_852');
var date = new Date(),
minute = ('00'+date.getMinutes()).slice(-2),
second = ('00'+date.getSeconds()).slice(-2);
try{
throw new Error();
}catch(e){
var loc = (e.stack.replace(/Error\n/).split(/\n/)[1]).replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
// var arr = loc.split(':'),
// col = parseInt(arr.pop()),
// line = parseInt(arr.pop());
$info.innerHTML += '<p>['+minute+':'+second+'] '+loc+'</p><p>'+msg+'</p><br/>';
}
}
判断 x 是否是整数
function isInteger(x) {
return parseInt(x, 10) === x;
}
function add(x, y) {
return x.toPrecision() + y.toPrecision()
}
console.log(add(0.1,0.2));
function add(num1, num2){
let r1, r2, m;
r1 = (''+num1).split('.')[1].length;
r2 = (''+num2).split('.')[1].length;
m = Math.pow(10,Math.max(r1,r2));
return (num1 * m + num2 * m) / m;
}
console.log(add(0.1,0.2)); //0.3
console.log(add(0.15,0.2256)); //0.3756
PhantomJS抓取网页并将它渲染成图片
var page = require('webpage').create();
page.settings.userAgent = 'WebKit/534.46 Mobile/9A405 Safari/7534.48.3';
page.settings.viewportSize = { width: 400, height: 600 };
page.open('http://m.bbc.co.uk/news/business', function (status) {
if (status !== 'success') {
console.log('Unable to load BBC!');
phantom.exit();
} else {
window.setTimeout(function () {
page.clipRect = { left: 0, top: 0, width: 400, height: 600 };
page.render('bbc-page1.png');
page.clipRect = { left: 0, top: 600, width: 400, height: 600 };
page.render('bbc-page2.png');
phantom.exit();
}, 2000);
}
});
复制与粘贴
<p>Email me at <a class="js-emaillink" href="mailto:matt@example.co.uk">matt@example.co.uk</a></p>
<p><button class="js-emailcopybtn"><img src="./images/copy-icon.png" /></button></p>
var copyEmailBtn = document.querySelector('.js-emailcopybtn');
copyEmailBtn.addEventListener('click', function(event) {
// Select the email link anchor text
var emailLink = document.querySelector('.js-emaillink');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// Now that we've selected the anchor text, execute the copy command
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy email command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
});
倒计时的JS
var time_distance;
var totleTime;
var stop;
function countdownTime(disTime){
time_distance =disTime;
totleTime=time_distance;
showTime();
}
function showTime(){
time_distance=totleTime;
var day=0,
hour=0,
minute=0,
second=0;//时间默认值
if(time_distance > 0){
day = Math.floor(time_distance / (60 * 60 * 24*1000));
hour = Math.floor(time_distance / (60 * 60*1000)) - (day * 24);
minute = Math.floor(time_distance / (60*1000)) - (day * 24 * 60) - (hour * 60);
second = Math.floor(time_distance/1000) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
}
if (hour <= 9) hour = '0' + hour;
if (minute <= 9) minute = '0' + minute;
if (second <= 9) second = '0' + second;
// 显示时间
$("#time_d").text(day+'天');
$("#time_h").text(hour+'时');
$("#time_m").text(minute+'分');
$("#time_s").text(second+'秒');
stop=setTimeout("showTime()",1000);
totleTime=totleTime-1000;
if(totleTime<1000){
$("#time_d").text('活动');
$("#time_h").text('已经');
$("#time_m").text('结束');
$("#time_s").text('。');
clearTimeout(stop);
}
}
一个数每隔一秒执行加1并打印出来
var count = (function() {
var timer;
var i = 0;
function change(tar) {
i++;
console.log(i);
if (i === tar) {
clearTimeout(timer);
return false;
}
timer = setTimeout(function() {
change(tar)
}, 1000)
}
return change;
})()
count(50)
onerror log
'use strict';
function errorHandler( message, source, lineno, colno, error){
var errorDiv = document.getElementById("error");
errorDiv.classList.remove("hide");
console.log("Error happened, message:", message);
console.log("On source file: ", source);
console.log("On line - col: ", lineno, "-", colno);
console.log("Error:", error);
try {
var ua = navigator.userAgent;
console.log("UA: ", ua);
} catch (e) {
console.log("Unable to get UA");
}
}
window.onerror = errorHandler;
javascript copy
<div class="line copyAsText">
<label for="bbcode" class="copyBtn">BBCode</label>
<input name="bbcode" value="[img]http://7sdream-rikka-demo.daoapp.io/files/95356e2f-7648-431f-8fe3-754d833d6cc1.png[/img]" disabled/>
</div>
'use strict';
function addCopyEventListener(url){
var divs = document.querySelectorAll("div.copyAsText");
for (var index in divs) {
if(!divs.hasOwnProperty(index)) {
continue;
}
var div = divs[index];
var input = div.querySelector("input");
var btn = div.querySelector("label");
if (url !== "") {
var template = input.getAttribute("data-template");
input.value = template.replace("${url}", url);
}
void function(btn, input){
btn.addEventListener("click", function(){
if (btn.disabled) {
return;
}
var res = false;
try {
input.disabled = false;
var section = window.getSelection();
section.removeAllRanges();
input.focus();
input.setSelectionRange(0, input.value.length);
res = document.execCommand("copy");
input.disabled = true
} catch(e) {
res = false;
}
if (res) {
var origin = btn.textContent;
btn.textContent = "Copied!";
btn.disabled = true;
setTimeout(function(){
btn.textContent = origin;
btn.disabled = false;
}, 2000);
} else {
window.prompt("Copy to clipboard: Ctrl+C, Enter", input.value);
}
});
}(btn, input);
}
}
addCopyEventListener("");
//https://github.com/imsobear/blog/issues/31
//只需要对相应的元素绑定 mouseenter 的事件,然后响应 selectText() 这个方法就 ok
function selectText (element) {
var text = element,
range,
selection;
if (body.createTextRange) {
// IE
range = body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
// Others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
} else {
return false;
}
}
把节点列表(NodeList)转换为数组
var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // 现在 NodeList 是一个数组
var arrayElements = Array.from(elements); // 这是另一种转换 NodeList 到 Array 的方法
var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
JavaScript实现字符串长度截取
function cutstr(str, len) {
var temp;
var icount = 0;
var patrn = /[^\x00-\xff]/;
var strre = "";
for (var i = 0; i < str.length; i++) {
if (icount < len - 1) {
temp = str.substr(i, 1);
if (patrn.exec(temp) == null) {
icount = icount + 1
} else {
icount = icount + 2
}
strre += temp
} else {
break
}
}
return strre + "..."
}
function $(id) {
return !id ? null : document.getElementById(id);
}
// 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:GET["t1"], GET["t2"], GET["t3"]
function get_get(){
querystr = window.location.href.split("?")
if(querystr[1]){
GETs = querystr[1].split("&")
GET =new Array()
for(i=0;i<GETs.length;i++){
tmp_arr = GETs[i].split("=")
key=tmp_arr[0]
GET[key] = tmp_arr[1]
}
}
return querystr[1];
}
/**
* 判断变量是否空值
* undefined, null, '', false, 0, [], {} 均返回true,否则返回false
*/
function empty(v){
switch (typeof v){
case 'undefined' : return true;
case 'string' : if(trim(v).length == 0) return true; break;
case 'boolean' : if(!v) return true; break;
case 'number' : if(0 === v) return true; break;
case 'object' :
if(null === v) return true;
if(undefined !== v.length && v.length==0) return true;
for(var k in v){return false;} return true;
break;
}
return false;
}
function backTop(btnId) {
var btn = document.getElementById(btnId);
var d = document.documentElement;
var b = document.body;
window.onscroll = set;
btn.style.display = "none";
btn.onclick = function() {
btn.style.display = "none";
window.onscroll = null;
this.timer = setInterval(function() {
d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
if ((d.scrollTop + b.scrollTop) == 0) clearInterval(btn.timer, window.onscroll = set);
},
10);
};
function set() {
btn.style.display = (d.scrollTop + b.scrollTop > 100) ? 'block': "none"
}
};
backTop('goTop');
mockjs让前端开发独立于后端
<script src="http://mockjs.com/dist/mock.js"></script>
<script>
//调用mock方法模拟数据
Mock.mock('http://laoyu', {
"errorcode": 0,//0表示成功,1表示错误
"message": "xx信息不完整", //弹出错误信息
});
//使用ajax进行测试
var xhr = XMLHttpRequest();
xhr.open("post","http://laoyu",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if((xhr.status>=200 && xhr.status<300) || xhr.status== 304){
var data = JSON.parse(xhr.responseText);
//因为reponseText返回的是字符串,将字符串转换成我们想要的JSON数据,这样就可以调用了
console.log(data); //在控制台中打印出返回的内容
}else{
alert("Request was unsuccessful: " + xhr.status);
}
}
}
</script>
rand num
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(10,100);
创建XMLHttpRequest对象
function createXHR(){
if(typeof XMLHttpRequest != "undefined"){
return new XMLHttpRequest();
}else if(typeof ActiveXObject != "undefined"){
if(typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp. 3.0","MSXML2.XMLHttp"],i,len;
for(i = 0,len=versions.length;i<len;i++){
try{
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
}catch(ex){
//跳过
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}else{
throw new Error("No XHR object available.");
}
}
var xhr = createXHR();
xhr.open("post","check.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if((xhr.status>=200 && xhr.status<300) || xhr.status== 304){
alert(xhr.responseText);
}else{
alert("Request was unsuccessful: " + xhr.status);
}
}
}
多行文本溢出显示省略号
var module = document.getElementById("clamp-this-module");
$clamp(module, {clamp: 3});
微信页面监听摇一摇事件,并伴有音效
<audio style="display: none;" src="http://xunlei.sc.chinaz.com/files/download/sound1/201410/5018.mp3" id="musicBox" preload="preload" controls></audio>
<script>
var SHAKE_THRESHOLD = 3000;
var last_update = 0;
var x=y=z=last_x=last_y=last_z=0;
var media;
media= document.getElementById("musicBox");
function init(){
last_update=new Date().getTime();
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion',deviceMotionHandler, false);
} else{
alert('not support mobile event');
}
}
function deviceMotionHandler(eventData) {
var acceleration =eventData.accelerationIncludingGravity;
var curTime = new Date().getTime();
if ((curTime - last_update)> 100) {
var diffTime = curTime -last_update;
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x +y + z - last_x - last_y - last_z) /
diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
media.play();
}
last_x = x;
last_y = y;
last_z = z;
}
}
window.onload = function(){
init();
}
</script>
鼠标向下滚动的时候header会消失
//设置下css,加个绿色的背景,明显
$('.sf-header').css({
background : '#CFC',
width: '100%'
});
//
$(document).scroll( function(){
var me = arguments.callee; //匿名函数可以 通过 arguments.callee 调用自己
me.doc = me.doc || $(document); //缓存 $(document);
me.head = me.head || $('.sf-header');
me.lastTop = me.lastTop || me.doc.scrollTop();
if( me.doc.scrollTop() < 20 || me.doc.scrollTop() > me.lastTop ){
//向下 或再 页面顶部,放在 头部
me.head.css({ position : 'relative' });
}else if( me.doc.scrollTop() < me.lastTop ){
//向上,悬浮
me.head.css({ position : 'fixed' });
}
me.lastTop = me.doc.scrollTop();
});
v2ex 的下一主题
window.location.href = 'https://www.v2ex.com/t/' + (Number(document.location.href.replace(/https:\/\/www\.v2ex\.com\/t\/(\d?)/i, '$1'))+1)
window.location.href.substring(23,29) * 1 + 1
location.href=location.href.split(/[/#]/)[4]*1+1
location.pathname.substring(3)
判断一个单词是否是回文
function checkPalindrom(str) {
return str == str.split('').reverse().join('');
}
去掉一组整型数组重复的值
let unique = function(arr) {
let hashTable = {};
let data = [];
for(let i=0,l=arr.length;i<l;i++) {
if(!hashTable[arr[i]]) {
hashTable[arr[i]] = true;
data.push(arr[i]);
}
}
return data
}
统计一个字符串出现最多的字母
function findMaxDuplicateChar(str) {
if(str.length == 1) {
return str;
}
let charObj = {};
for(let i=0;i<str.length;i++) {
if(!charObj[str.charAt(i)]) {
charObj[str.charAt(i)] = 1;
}else{
charObj[str.charAt(i)] += 1;
}
}
let maxChar = '',
maxValue = 1;
for(var k in charObj) {
if(charObj[k] >= maxValue) {
maxChar = k;
maxValue = charObj[k];
}
}
return maxChar;
}
生成斐波那契数组
function getFibonacci(n) {
var fibarr = [];
var i = 0;
while(i<n) {
if(i<=1) {
fibarr.push(i);
}else{
fibarr.push(fibarr[i-1] + fibarr[i-2])
}
i++;
}
return fibarr;
}
闭包
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function(test) {
console.log("inner func: this.foo = " + test.foo); //'bar'
console.log("inner func: self.foo = " + self.foo);
}(self));
}
};
myObject.func();
for(var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i); // 555555
}, 1000);
}
for(var i = 0; i < 5; i++) {
(function(i) {
setTimeout(function() {
console.log(i); //0 , 1 , 2 , 3 , 4
}, 1000);
})(i)
}
function add(num1, num2){
let r1, r2, m;
r1 = (''+num1).split('.')[1].length;
r2 = (''+num2).split('.')[1].length;
m = Math.pow(10,Math.max(r1,r2));
return (num1 * m + num2 * m) / m;
}
console.log(add(0.1,0.2)); //0.3
console.log(add(0.15,0.2256)); //0.3756
10 的阶乘
console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));
逻辑与返回第一个是 false 的操作数 或者 最后一个是 true 的操作数
如果某个操作数为 false ,则该操作数之后的操作数都不会被计算
console.log(1 && 2 && 0); //0
console.log(1 && 0 && 1); //0
console.log(1 && 2 && 3); //3
逻辑或返回第一个是 true 的操作数 或者 最后一个是 false 的操作数
console.log(1 || 2 || 0); //1
console.log(0 || 2 || 1); //2
console.log(0 || 0 || false); //false
如果某个操作数为 true ,则该操作数之后的操作数都不会被计算
如果逻辑与和逻辑或作混合运算,则逻辑与的优先级高
if 中,[] 和 {} 都表现为 true
Unicode 编码转换
function encodeUTF8(str){
var temp = "",rs = "";
for( var i=0 , len = str.length; i < len; i++ ){
temp = str.charCodeAt(i).toString(16);
rs += "\\u"+ new Array(5-temp.length).join("0") + temp;
}
return rs;
}
function decodeUTF8(str){
return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
encodeUTF8('中文')
"\u4e2d\u6587"
decodeUTF8('\u4e2d\u6587')
"中文"
//https://segmentfault.com/q/1010000000095710
var decToHex = function(str) {
var res=[];
for(var i=0;i < str.length;i++)
res[i]=("00"+str.charCodeAt(i).toString(16)).slice(-4);
return "\\u"+res.join("\\u");
}
var hexToDec = function(str) {
str=str.replace(/\\/g,"%");
return unescape(str);
}
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var str = 'JavaScript高级程序设计';
console.log(decodeHtmlEntity(str));//JavaScript高级程序设计
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
var str = '高级程序设计';
console.log(encodeHtmlEntity(str));//高级程序设计
function u2str(text){
return $('<p></p>').html(text).text();
}
数组反转
var test = [
[1, 0, 4, 3, 2],
[0, 4, 3, 2, 1],
[4, 3, 2, 1, 0],
[3, 2, 1, 0, 4]
];
test.forEach(arr => console.log(reversal(arr)));
// 反转
function reversal(arr) {
let len = arr.length;
// get max
let max = arr[0];
let index = 0;
arr.forEach((v, i) => {
if (v <= max) return;
max = v;
index = i;
});
// strat re
let tmp = arr.reverse().concat(arr, arr);
let newIndex = len - 1 - index + len;
return tmp.slice(newIndex - index, newIndex + len - index);
}
var arr = [1, 0, 4, 3, 2];
反转为
var arr = [2, 3, 4, 0, 1];
chrome console
dir($('selector')) 会返回匹配选择器的DOM元素的所有属性
获取某个DOM元素绑定的事件 getEventListeners($('#firstName')).click[0].listener
深拷贝 对象和数组
var cloneObj = function(obj){
var str, newobj = obj.constructor === Array ? [] : {};
if(typeof obj !== 'object'){
return;
} else if(window.JSON){
str = JSON.stringify(obj), //系列化对象
newobj = JSON.parse(str); //还原
} else {
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' ?
cloneObj(obj[i]) : obj[i];
}
}
return newobj;
};
//jQuery.extend第一个参数可以是布尔值,用来设置是否深度拷贝的:
jQuery.extend(true, { a : { a : "a" } }, { a : { b : "b" } } );
jQuery.extend( { a : { a : "a" } }, { a : { b : "b" } } );
ajax提交2个相同的键值
在form表单中有两个同name名为'tag',然后在ajax提交的时候直接用serialize进行了序列化
$.post('url', {
tags: 7,
tags: 128,
})
或者
var str='tags=7&tags=128';
$.ajax({
type:"post",
url:"http://localhost/",//地址自己改
data:str,
async:true
});
精度丢失
str = '{"a":1234567890123456789,"b":1234567890123239}';
str = str.substr(1);
str = str.substr(0,str.length-1);
str.split(",");
arr = str.split(",");
obj = {};
arr.forEach(function(el,index){
var arr1 = el.split(":");
//obj[arr1[0]]=""+arr1[1];
obj[arr1[0]]=(Number.isSafeInteger(arr1[1])?arr1[1]:(""+arr1[1]));
});
console.dir(obj);
var str = '{"a":1234567890123456789, "b": 1234567890123456789, "c": 1234567890123456789}';
var json = JSON.parse(str.replace(/\:\ *(\d*?)\ *(\,|\})/g, (a, b, c) => `:"${b}"${c}`));
console.log(json);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。