欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js的常用小技巧

程序员文章站 2022-03-11 08:23:40
...

//类对象转成数组

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));   var domNodes = Array.prototype.slice.call(arguments);


向下取整:
var a = ~~1.2; //1
这个补充一下,还可以用位右移符>>
var a = 3.4>>0; //3 

但是两者最好都只用在正整数上,因为只是舍掉了小数部分。Math.floor(-1.2)应该为-2,这两种方法的结果为-1

转数字
var time = + new Date();

设默认值
function foo(bar){
    var foobar = bar || 'default'; 
    //bar 为 undefined, null, "", 0, false, NaN 时最后都得到'default'
}

//坑
[]||"aa"; //[]
{}||"aa"; //SyntaxError
({})||"aa";//Object {}

NaN的坑
//NaN - 不是一个数字
isNaN(a);
//检查是不是 "不是一个数字" ..

isNaN(null);//false
//实际上是null被转为0了,表面上"null 不是一个 不是数字 的东西"。wtf...

UNICODE 用作变量名
var \u4f60\u597d = "\u4f60\u597d";
var b = {};
b.\u4f60\u597d = \u4f60\u597d;
console.log(b);//Object {你好: "你好"}
console.log(b.你好);// "你好"
console.log(b.\u4f60\u597d);// "你好"

console.log("你"==="\u4f60");//true

数组传递和复制
var a = [1,2,3];
var b = a;
delete b[1];
console.log(a);//[1, undefined × 1, 3]

var a = [4,5,6];
var b = a.slice(0);
delete b[1];
console.log(a);//[4,5,6]
console.log(b);//[4, undefined × 1,6]

对象与Function
console.log(typeof Function);//"function"
console.log(typeof Object);//"function"

函数声明
aa();
function aa(){return true;} //true

bb();
var bb = function(){return true;} //TypeError

toString()
2.toString();//SyntaxError
2 .toString(); //"2"
2..toString(); //"2"
(2).toString(); //"2"

[1,[2,"abc","",0,null,undefined,false,NaN],3].toString();
//"1,2,abc,,0,,,false,NaN,3"

for in 暴露原型链属性
Object.prototype.foo = 1;

var obj = new Object();
obj.bar = 1;
for(var p in obj){
    console.log(p);//bar,foo 都遍历出来了。可以用hasOwnProperty()过滤原型链属性

}

switch代替if else
 switch (true) {  
        case (a > 10):  
            do_something();
            break;
        case (a < 100):  
            others();  
            break;  
        default:
            ;  
            break;  
    };  
 


漂亮的随机码

Math.random().toString(16).substring(2); //14位
Math.random().toString(36).substring(2); //11位


合并数组:
var a = [1,2,3];
var b = [4,5,6];
Array.prototype.push.apply(a, b);
console.log(a); //[1,2,3,4,5,6]
用0补全位数:
function prefixInteger(num, length) {
  return (num / Math.pow(10, length)).toFixed(length).substr(2);
}

交换值:
a= [b, b=a][0];
将一个数组插入另一个数组的指定位置:
var a = [1,2,3,7,8,9];
var b = [4,5,6];
var insertIndex = 3;
a.splice.apply(a, Array.concat(insertIndex, 0, b));
// a: 1,2,3,4,5,6,7,8,9
快速取数组最大和最小值
Math.max.apply(Math, [1,2,3]); //3
Math.min.apply(Math, [1,2,3]); //1

条件判断:
var a = b && 1;
//相当于:
if (b) {
  a = 1;
}else {
  a = b;
}

var a = b || 1;
//相当于
if (b) {
  a = b;
} else {
  a = 1;
}

判断数组:
Object.prototype.toString.call([]) === '[object Array]'; 

判断IE:
var ie = /*@cc_on [email protected]*/false;

取整:
a = 5.2|0

string转数字
a = +'123'

4. 去除数组中重复的值:
function removeRepeat(arr){
  return arr.filter(function(elem, pos) {
    return arr.indexOf(elem) == pos;
  });
}

var arr = new Array("1","2","3","4","4","4","4","5");
var newArr = removeRepeat(arr);
console.log(newArr); //1,2,3,4,5
function sum(arr){ return arr.reduce(function(s,n){ return s+n }); } var arr = new Array(1,2,3,4); console.log(sum(arr)); // 10


6. 寻找数组中的最大数
var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxNumber = Math.max.apply(null, numbers);
console.log(maxNumber);
判断是否为数组
 function isArray(arr){ return arr ? Object.prototype.toString.call(arr) === '[object Array]' : false }

转数字
var time = + new Date();


  • false => ![]
  • true => !![]
  • undefined => [][[]]
  • NaN => +[![]]
  • 0 => +[]
  • 1 => +!+[]
  • 2 => !+[]+!+[]
  • 10 => [+!+[]]+[+[]]
  • Array => []
  • Number => +[]
  • String => []+[]
  • Boolean => ![]
  • Function => []["filter"]
  • eval => []["filter"]["constructor"]( CODE )()
  • window => []["filter"]["constructor"]("return this")()

http://www.jsfuck.com/