Web-JavaScript-JavaScript 类型转换
【摘要】 <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>JavaScript 类型转换</title></head><body> <!--typeof操作符--> <p> typeof 操作符返回变量、对象、函数、表达式的类型。</p> <p id="demo"></p> <script> ...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript 类型转换</title>
</head>
<body>
<!--typeof操作符-->
<p> typeof 操作符返回变量、对象、函数、表达式的类型。</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof NaN + "<br>" +
typeof false + "<br>" +
typeof [1, 2, 3, 4] + "<br>" +
typeof {
name: 'john',
age: 34
} + "<br>" +
typeof new Date() + "<br>" +
typeof
function() {} + "<br>" +
typeof myCar + "<br>" +
typeof null;
</script>
<!--constructor 属性-->
<p>constructor属性返回变量或对象的构造函数.</p>
<p id="demo1"></p>
<script>
document.getElementById("demo1").innerHTML = "john".constructor + "<br>" + (3.14).constructor + "<br>" + false.constructor + "<br>" + [1, 2, 3, 4].constructor + "<br>" + {
name: "john",
age: 34
}.constructor + "<br>" + new Date().constructor + "<br>" + function() {}.constructor;
</script>
<!--constructor 属性-->
<p>判断是否为数组。</p>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo2").innerHTML = isArray(fruits);
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>
<p>判断是否为日期。</p>
<p id="demo3"></p>
<script>
var myDate = new Date();
document.getElementById("demo3").innerHTML = isDate(myDate);
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>
<p>String()方法可以将数字转换为字符串</p>
<p id="demo4"></p>
<script>
var x = 123;
document.getElementById("demo4").innerHTML = String(x) + "<br>" + String(123) + "<br>" + String(100 + 23);
</script>
<p>toString()方法将数字转为字符串</p>
<p id="demo5"></p>
<script>
var x = 123;
document.getElementById("demo5").innerHTML = x.toString() + "<br>" + (123).toString() + "<br>" + (100 + 23).toString();
</script>
<p> typeof 操作符返回变量或表达式的类型。</p>
<button οnclick="myFunction()">点我</button>
<p id="demo6"></p>
<script>
function myFunction() {
var y = "5";
var x = +y;
document.getElementById("demo6").innerHTML =
typeof y + "<br>" + typeof x;
}
</script>
<p>typeof操作符返回变量或表达式的类型</p>
<button οnclick="myFunction()">点我</button>
<p id="demo7"></p>
<script>
function myFunction() {
var y = "john";
var x = +y;
document.getElementById("demo7").innerHTML = typeof + "<br>" + x;
}
</script>
</body>
</html>
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)