Javascript基础语法: 变量、数据类型、类型转化
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test5</title>
</head>
<body>
<p>点击这里来创建变量,并显示结果。</p>
<button onclick="myFunction()">点击这里</button>
<p id="1"></p>
<script>
function myFunction(){
var lastname="Doe", age=30, job="carpenter";
document.getElementById("1").innerHTML=lastname + "<br>" + age + "<br>" + job;
}
</script>
<p>JavaScript 字符串</p>
<p>您可以在字符串中使用引号,只要不匹配包围字符串的引号即可:</p>
<script>
var carname1="Volvo XC60";
var carname2='Volvo XC60';
var answer1='It\'s alright';
var answer2="He is called \"Johnny\"";
var answer3='He is called "Johnny"';
document.write(carname1 + "<br>")
document.write(carname2 + "<br>")
document.write(answer1 + "<br>")
document.write(answer2 + "<br>")
document.write(answer3 + "<br>")
</script>
<p>JavaScript 数组
下面的代码创建名为 cars 的数组:</p>
<script>
var i;
// var cars = new Array();
// cars[0] = "Saab";
// cars[1] = "Volvo";
// cars[2] = "BMW";
var cars=new Array("Saab","Volvo","BMW");
for (i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
</script>
<p>声明变量类型
当您声明新变量时,可以使用关键词 "new" 来声明其类型:</p>
<script>
var carname=new String;
var x= new Number;
var y= new Boolean;
var cars= new Array;
var person= new Object;
</script>
<p> String() 方法可以将数字转换为字符串。</p>
<p id="demo"></p>
<script>
var x = 123;
document.getElementById("demo").innerHTML =
String(x) + "<br>" +
String(123) + "<br>" +
String(100 + 23);
</script>
<p>你可以使用 typeof 操作符来查看 JavaScript 变量的数据类型。</p>
<p> typeof 操作符返回变量、对象、函数、表达式的类型。</p>
<p id="2"></p>
<script>
document.getElementById("2").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>
</body>
</html>
|