美文网首页
JavaScript 类型转换

JavaScript 类型转换

作者: 小弱鸡 | 来源:发表于2016-08-02 13:32 被阅读25次

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

  • String
  • Number
  • Boolean
  • Object
  • Function

3 种对象类型:

  • Object
  • Date
  • Array

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

  • null
  • undefined
    可以使用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] }

JavaScript 类型转换###

JavaScript 变量可以转换为新变量或其他数据类型:

  • 通过使用 JavaScript 函数
  • 通过 JavaScript 自身自动转换

/**

  • string转化
    */
    console.log(String(123));
    console.log(String(100 + 23));
string转数字

![屏幕快照 2016-08-02 上午11.43.52.png](https://img.haomeiwen.com/i1939330/8c7fe9a83b8903df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
待增加······

相关文章

网友评论

      本文标题:JavaScript 类型转换

      本文链接:https://www.haomeiwen.com/subject/awlxsttx.html