一,效果圖。 二,代碼。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JavaScript 類型轉換</title> </head> <body> <!--typeof操作符--> <p> typeof 操作符返回變數、對象 ...
一,效果圖。
二,代碼。
<!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 onclick="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 onclick="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>
參考資料:《菜鳥教程》