1、字符串转换为数值
常规方法:
varvar1 = parseInt("2");
varvar2 = parseFloat("2");
varvar3 = Number("2");
varvar3 = newNumber("2");简便方法:
varvar1 = +("2");
console.log(arr);//Number2、将其他类型转换为boolean类型
在JavaScript中,所有值都能隐式的转化为Boolean类型:
0 == false; // true
1 == true; // true
''== false// true
null== false// true我们也可以显示转化为Boolean类型:
vara = Boolean("Hello"); //true更简单的方法:
vara = "Hello";
varb = !!a;
console.log(b);//true3、阻止别人在iframe中加载你的页面
防止把你的网页通过iframe嵌入它自己的网页,这段代码应该放在每个页面的head中。
if(top !== window) {
top.location.href = window.location.href;
}4、将arguments参数对象转换为数组
在JavaScript中,函数中的预定义变量arguments并非一个真正的数组,而是一个类似数组的对象。 它具有length属性,但是没有数组对象的slice, push, sort等函数,而这些有时我们经常在函数里用到,所以我们需要把参数转换为真正的数组:
functionchangeArgu() {
vararr = Array.prototype.slice.call(arguments, 0);
returnarr;
}5、获取数字数组中的最大值
常规方法:
vararr = [1, 5, 4, 12355, 43, 123, 123, 3, 4454, 43];
varmax = arr[0];
for(vari inarr) {
if(arr[i] > max) {
max = arr[i];
}
}
/*
循环也可能是:
for(var i = 0 ,j = arr.length; i < j; i++) {
if(arr[i] > max) {
max = arr[i];
}
}
*/
console.log(max);简便方法:
vararr = [1, 5, 4, 12355, 43, 123, 123, 3, 4454, 43];
varmax = Math.max.apply(null, arr);
console.log(max);6、修正类似于0.1+0.2 != 0.3的错误
在JavaScript中,数字是基于IEEE754的数值,所以会出现浮点运算误差的情况,这是使用IEEE754的通病,不是语言本身的问题:
varnum = 0.1 + 0.2; // 0.30000000000000004
console.log(num == 0.3); // false修正方法:
varnum = 0.1 + 0.2; // 0.30000000000000004
console.log(num);
/*你可以通过toFixed方法指定四舍五入的小数位数:*/
console.log(num.toFixed()); // "0"
console.log(num.toFixed(1)); // "0.3"7、整数前补0
普通方法:
/*注意,这里的n表示数字num补0后的位数*/
functionaddZero(num, n) {
varlen = num.toString().length;
while(len < n){
num = "0"+ num;
len++;
}
returnnum;
}
console.log(addZero(5,8)); //00000005简单方法:
functionaddZero(num, n) {
y='00000000000000000000000000000'+num;
/*
这里0的数目可调整
*/
returny.substr(y.length-n);
}
console.log(addZero(5,8)); //00000005