Javascript的数据类型和转换

JavaScript 数据类型

在 JavaScript 中有 5 种不同的数据类型:

  • string
  • number
  • boolean
  • object
  • function

3 种对象类型:

  • Object
  • Date
  • Array

2 个不包含任何值的数据类型:

  • null
  • undefined

js判断数组类型的方法

方法一:typeof 操作符

你可以使用 typeof 操作符来查看 JavaScript 变量的数据类型。

typeof "John"                 // 返回 string 
typeof 3.14                   // 返回 number
typeof NaN                    // 返回 number
typeof false                  // 返回 boolean
typeof [1,2,3,4]              // 返回 object
typeof {name:'John', age:34}  // 返回 object
typeof new Date()             // 返回 object
typeof function () {}         // 返回 function
typeof myCar                  // 返回 undefined (如果 myCar 没有声明)
typeof null                   // 返回 object

请注意:

  • NaN 的数据类型是 number
  • 数组(Array)的数据类型是 object
  • 日期(Date)的数据类型为 object
  • null 的数据类型是 object
  • 未定义变量的数据类型为 undefined

如果对象是 JavaScript Array 或 JavaScript Date(也就是在对引用类型时) ,我们就无法通过 typeof 来判断他们的类型,因为都是 返回 object。

方法二:constructor 属性

constructor 属性返回所有 JavaScript 变量的构造函数。

"John".constructor                 // 返回函数 String()  { [native code] }
(3.14).constructor                 // 返回函数 Number()  { [native code] }
false.constructor                  // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor              // 返回函数 Array()   { [native code] }
{name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }
new Date().constructor             // 返回函数 Date()    { [native code] }
function () {}.constructor         // 返回函数 Function(){ [native code] }

你可以使用 constructor 属性来查看对象是否为数组 (包含字符串 "Array"):

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}

你可以使用 constructor 属性来查看对象是否为日期 (包含字符串 "Date"):

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}

方法三:instanceof

instanceof 用于判断一个变量是否某个对象的实例,是一个三目运算式

因为typeof对对象类型束手无策,所以我们可以使用instanceof

console.log(Object instanceof Object);//true 
console.log(Function instanceof Function);//true 
console.log(Number instanceof Number);//false 
console.log(String instanceof String);//false 
 
console.log(Function instanceof Object);//true 
 
console.log(Foo instanceof Function);//true 
console.log(Foo instanceof Foo);//false

类型转换

隐式类型

隐式类型转换和java中大不相同,在js中数据类型不严格,没有浮点和整型,这里的隐式类型转换指的是字符串和数值类型之间的转换,在进行字符串和数字之间进行减乘除取模运算或者进行比较运算时,他会自动把字符串转换为数字。转换数字的默认方法是调用Number(),进行加法运算则是将数字看成字符串进行拼接. 

var x = "123";

var y = 121;

alert(x+y);//"123121;

alert(x-y);//2

alert(x*y);//14883

alert(x/y);//1.016528256198346

alert(x%y);//2

alert(x>y);//true

alert(x==y);//false

alert("123a">y);//false诡异

alert('212' == 212) //true

5 + null    // 返回 5         null 转换为 0
"5" + null  // 返回"5null"   null 转换为 "null"
"5" + 1     // 返回 "51"      1 转换为 "1"  
"5" - 1     // 返回 4         "5" 转换为 5

原文地址:https://www.cnblogs.com/sophiazhu/p/10435495.html