整理幾個JavaScript常用的函數


/*判斷是否為數字*/
var t1= new Boolean(true);
var t2= new Boolean(false);
var t3= new Date();
var t4= new String("999.88");
var t5= new String("999 888");

document.write(Number(t1)+ "
");
document.write(Number(t2)+ "
");
document.write(Number(t3)+ "
");
document.write(Number(t4)+ "
");
document.write(Number(t5)+ "
");
/*--result--*/
1
0
1345824400758
999.88
NaN


/*The isNaN() function is supported in all major browsers.*/
document.write(isNaN(123)+ "
");
document.write(isNaN(-1.23)+ "
");
document.write(isNaN(5-2)+ "
");
document.write(isNaN(0)+ "
");
document.write(isNaN("Hello")+ "
");
document.write(isNaN("2005/12/12")+ "
");
/*--result--*/
false
false
false
false
true
true

/*這剛好跟上面的相反,判斷為數字為True*/

document.write(isFinite(123)+ "
");
document.write(isFinite(-1.23)+ "
");
document.write(isFinite(5-2)+ "
");
document.write(isFinite(0)+ "
");
document.write(isFinite("Hello")+ "
");
document.write(isFinite("2005/12/12")+ "
");
/*--result--*/
true
true
true
true
false
false

/*快速四捨五入,但回傳為字串*/
var num = 5.56789;
document.write(num.toFixed(3)+ "
");
document.write((num.toFixed(3)+2)+ "
");
var num2 = 55.6789;
document.write(num2.toFixed(3)+ "
");
document.write((num2.toFixed(3)+2)+ "
");
/*--result--*/
5.568
5.5682
55.679
55.6792