分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

js数据类型转换

发布时间:2023-09-06 02:29责任编辑:彭小芳关键词:js数据类型

1.通过typeof查看数据类型

typeof 3.14 ??????????????????// 返回 numbertypeof NaN ???????????????????// 返回 numbertypeof "John" ????????????????// 返回 string typeof false ?????????????????// 返回 booleantypeof [1,2,3,4] ?????????????// 返回 objecttypeof {name:‘John‘, age:34} ?// 返回 objecttypeof new Date() ????????????// 返回 objecttypeof function () {} ????????// 返回 functiontypeof myCar ?????????????????// 返回 undefined(如果myCar没有声明)typeof undefined ?????????????// 返回 undefinedtypeof null ??????????????????// 返回 object

typeof的返回只有number、string、boolean、object、function、undefined五种类型

如果要查看的是数组、对象、日期、或者null,返回值都是object,无法通过typeof来判断他们的类型

2.通过constructor属性返回构造函数

(1234).constructor ??????????????????//function Number() { [native code] }NaN.constructor ?????????????????????//function Number() { [native code] }‘hello‘.constructor ?????????????????//function String() { [native code] }false.constructor ???????????????????//function Boolean() { [native code] }[1,2,3,4].constructor ???????????????//function Array() { [native code] }{name:‘John‘, age:34}.constructor ???//function Object() { [native code] }new Date().constructor ??????????????//function Date() { [native code] }function(){}.constructor ????????????//function Function() { [native code] }

constuction属性返回的构造函数有七种,unll和undefined没有构造函数

3.自动类型转换

数字 + 字符串 : 将数字转化为字符串,再与后面字符串的进行拼接

数字 + 布尔值:true转化为1,false转化为0,再与数字进行相加

字符串 + 布尔值:按照字符串进行拼接

document.getElementById("demo").innerHTML = myVar;myVar = {name:"Fjohn"} ?// toString 转换为 "[object Object]"myVar = [1,2,3,4] ??????// toString 转换为 "1,2,3,4"myVar = new Date() ?????// toString 转换为 "Fri Jul 18 2014 09:08:55 GMT+0200"

4.数字、布尔值、日期强制转化为字符串

String(123)、(123).toString()都可将数字转化为字符串

String(true)、false.toString()都可将数字转化为字符串

String(new Date()) 、(new Date()).toString()都可将日期转化为字符串

5.数字类型的字符串、布尔值、日期强制转化为数字

Number(‘3.14‘)可将字符串3.14转化为数字3.14,Number(‘‘)返回0,Number("99 88")返回NaN  

Number(false)返回0,Number(true) 返回1

d = new Date(),Number(d)和d.getTime()可将日期转换为数字

parseInt( ) 将浮点数、字符串类型的数字、以数字开头的字符串转化为整数,转换失败时会得到NaN

parseFloat()强制转换为浮点数

6.eval():将字符串强制转换为表达式并返回结果,例如eval(‘1+4‘)=5

js数据类型转换

原文地址:https://www.cnblogs.com/Forever77/p/10247986.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved