自己平时收集的JS小知识点。
typeof void 0 //"undefined"
undefined === void 0 //true
undefined == void 0 //true
null == void 0 //true
"undefined" == void 0 //false
undefined
表示未定义 ; null
表示值为空。
typeof null //"object"
undefined == null //true
undefined === null //false
Infinity //Infinity
1.7976931348623157E+1030899 //Infinity
-1.7976931348623157E+1030899 //-Infinity
洗牌算法: Fisher-Yates shuffle.
var shuffle = function(arr , n) {
if (n == null) n = Infinity;
var n = Math.max(Math.min(n, arr.length), 0);
var last = arr.length - 1;
for (var index = 0; index < n; index++) {
var rand = random(index, last);
var temp = arr[index];
arr[index] = arr[rand];
arr[rand] = temp;
}
return arr.slice(0, n);
};
var random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
稀疏数组最简单的解释就是有length属性,但是无法通过 forEach遍历出来。
var a = Array(3); //[undefined × 3]
a.forEach(function(v ,i){console.log(v,i)})//没有元素
密集数组:
var a = Array.apply(null, Array(3)); //[ undefined, undefined, undefined ]
//等价于
Array(undefined, undefined, undefined)
Promise都是最先执行的,setTimeout(0)、setImmediate和requestAnimationFrame顺序不确定。 process.nextTick是Nodejs的API,比Promise更早执行。
process.nextTick是不会进入异步队列的,而是直接在主线程队列尾强插一个任务,虽然不会阻塞主线程,但是会阻塞异步任务的执行,如果有嵌套的process.nextTick,那异步任务就永远没机会被执行到了。
/**
* [downloadFile 文件下载]
* @param {[type]} fileName [description]
* @return {[type]} [description]
*/
function downloadFile(fileId , fileName){ //不要用 ie
if ( !fileId ) return;
var aLink = document.createElement('a');
aLink.href = 'http://wwww.test.com/download?id='+fileId;
aLink.download = fileName ? fileName : fileId;
if (navigator.userAgent.indexOf("Chrome") >= 0 ) {
aLink.click();
}else{
window.open(aLink.href);
}
};
var style ,head , css='body{background:pink;}' , document = window && window.document;
try{
style = document.createElement("style");
style.type = "text/css";
style.textContent = css;
head = document.head ? document.head : document.getElementsByTagName('head')[0];
head.appendChild(style);
}catch(e){
style = document.createStyleSheet();
style.cssText = css;
}