您的位置:首页 > Web前端 > JavaScript

初学者可以用的js小技巧

2018-01-26 17:57 176 查看


1. 取整同时转成数值型

var a = '10.567890' | 0 ;
console.log("a=" + a + ", ");   // a=10
var b = '10.567890' ^ 0 ;
console.loge("b=" + b + ", ");   //b=10
var c = -2.23456789 | 0 ;
console.log("c=" + c + ", ");  //c=-2
var d = ~~-2.23456789 ;
console.log("d=" + c + ", ");  //d=-2



2. 日期转数值

var date1 = +new Date();
console.log("date1 = " + date1 + ", " ) //date1 = 1482564863680



3. 类数组对象转数组

var arr = [].slice.call(arguments);



4. 漂亮的随机码:

var num1 = Math.random().toString(16).substring(2); //14位
var num2 = Math.random().toString(36).substring(2); //11位
console.log("num1 = " + num1 + ", ") // num1 = 550b8c6863cd9
console.log("num2 = " + num2 + ", ") //num2 = ja9gaaogkpkupgf2zaw1p2e29



5.合并数组

var arr1 = [1,2,3];
var arr2 = [4,5,6];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1 + "<br/>"); //[1,2,3,4,5,6]



6.用0补全位数

function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}



7.交换值

var ch1 = 7;
var ch2 = 3;
[ch2, ch2=ch1][0];
console.log(ch2 + " , ") //7



8. 将一个数组插入另一个数组的指定位置:

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));
console.log(a) // a: 1,2,3,4,5,6,7,8,9



9. 快速取数组最大和最小值

console.log(Math.max.apply(Math, [1,2,3]) + " , ")  //3
console.log( Math.min.apply(Math, [1,2,3]) + " , ") //1



10. 条件判断:

1)
var b=0;
var a = b && 1;
console.log(a + " , ") // 0
var c=3;
var d = c && 1;
console.log(d + " , ") // 1
相当于
if (b) {  a = 1 }
2)
var a = b || 1;
相当于
if (b) {
a = b;
} else {
a = 1;
}



11. 判断IE:

var ie = /*@cc_on !@*/false;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js属性