09.js类型转换

1.js数据类型

String,Number,Boolean,Object,Function
三种对象类型:Object,Date,Array
不包含任何值的数据类型:null,undefined

2.typeof操作符

可以使用typeof操作符来查看js变量的数据类型
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var a = 0;
    document.write(typeof a); //number
    document.write(typeof NaN); //number
    document.write(typeof 3.14); //number
    document.write(typeof "bob"); //string
    document.write(typeof [1,2,3,4]); //object
    document.write(typeof {name:"bob"}); //object
    document.write(typeof new Date()); //object
    document.write(typeof null); //object
    document.write(typeof function () {}); //function
    document.write(typeof mycar); //undefined
</script>
</body>
</html>

注意
NaN的数据类型是number
数组array的数据类型是object
日期Date的数据类型是object
null的数据类型是object
未定义变量的数据类型是undefined
如果对象是JavaScript Array或者JavaScript Date,我们无法通过typeof来判断他们的类型,因为返回的都是object

3.类型转换

1.数字转换成字符串

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
   let a = 2;
   //第一种
   let a1 = String(a)
   document.write(typeof a1); //String

    //第二种
   let a2 = a.toString();
    document.write(typeof a2); //String
</script>
</body>
</html>

2.将日期转换成字符串

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

   //第一种
   let a1 = String(Date);
   document.write(Date());//Thu Jul 22 2021 16:35:35 GMT+0800 (中国标准时间)
   document.write(typeof a1); //String

    //第二种
   let a2 = Date.toString();
    document.write(typeof a2); //String
</script>
</body>
</html>

Date()中一些常用的方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var date = new Date();
    document.write(date.getDate()); //从Date对象返回一个月中的某一天
    document.write(date.getDay()); //从Date对象返回一周中的某一天
    document.write(date.getFullYear()); //从Date以四位数字返回年份
    document.write(date.getHours()); //返回Date对象的小时
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值