4、js内置函数

前言:
上一篇我介绍了函数的基本概念,和一些简单的Demo。其实很多函数是js内置的,我们无需自己去写,直接拿过来用即可。
内置函数分为全局函数和js内置对象的函数
区别:全局函数不属于任何一个内置对象。理论上,js的任何一个对象都可以用全局函数。全局属性和函数可用于所有内建的 JavaScript 对象。
菜鸟:http://www.runoob.com/jsref/jsref-obj-global.html
W3c:http://www.w3school.com.cn/jsref/jsref_obj_global.asp

全局函数【陆续补充中】

Number() 函数
把对象的值转换为数字。如果对象的值无法转换为数字,那么 Number() 函数返回 NaN。

var test1= new Boolean(true);//布尔对象
var test2= new Date();//日期对象
var test3= new String("999");//字符串对象
var test4= new String("999 888");//字符串对象
console.log(Number(test1));
console.log(Number(test2));
console.log(Number(test3));
console.log(Number(test4));

[Web浏览器] "1"
[Web浏览器] "1462289656237"
[Web浏览器] "999"
[Web浏览器] "NaN"

 

String()函数:
可以将任何类型的值转换为字符串,包括null转换为'null'、undefined转换为'undefined'。

var x=123;
var y=String(x);
console.log(x +"类型是:"+typeof x);//123类型是:number
console.log(y +"类型是:"+typeof y);//123类型是:string

isNaN()函数
isNaN(x)判断是不是非数,x为空或者非数的时候满足条件。比如isNaN(5/0)就成立。
总之大致一句话总结:只要不是数字,都是trtue
通常用于检测值的结果,判断它们表示的是否是合法的数字。

console.log(isNaN(1))//false
console.log(isNaN(2-1))//false
console.log(isNaN(5/0))//false
console.log(isNaN("5"))// false【注】

console.log(isNaN(0/0))//0除以0结果为NaN,true
console.log(isNaN("5-2"))//true
console.log(isNaN("A"))//true
//【注】:为何此处也行,因为因为 "5"==5, js会自动转换!!!所以必须判断类型,就诞生了typeof函数。如下代码
console.log("5"-"3")//结果打印2
console.log("5-3")//结果打印5-3
原文地址:https://www.cnblogs.com/dshvv/p/5467530.html