<script>
alert("hello")
</script>
<script>
document.write("hello")
</script>
<script>
console.log("hello")
</script>
双引号内用单引号
<body>
<div onclick="alert('hello');">
点
div>
body>
添加
可以放在head也可放在body(最好在body最后)
引入
<script src="路径">
script>
引入后,原script内写的内容无效
//
/* 内容*/
直接初始化
<script>
var x=100;
var y=x+300;
document.write(y);
</script>
先定义后赋值
<script>
var x;
x=100;
var y=x+300;
document.write(y);
</script>
多个变量、表达式之间用逗号表示
若给y加上双引号,则输出y,而不是400
除了以上包括浮点型(小数,,科学计数法)
输入的值最后都会输出为十进制
前缀:二进制0b,八进制0,十六进制0x
取值
变量声明了,但是未赋值
也可直接写为var a=undefined;
为未来赋值做准备 var a =null
想赋值了直接写a=某值
<script>
var a=1e3
document.write(a)
document.write(typeof a)
script>
<script>
var a="1e3"
document.write(a)
document.write(typeof a)
script>
<script>
var a=1e3
document.write(typeof typeof a)
script>
<script>
var a=1e3
document.write(a)
document.write(typeof a+100)
document.write(typeof (a+100))
var b=null
document.write(b)
script>
NaN也为数值类型
<script>
var a=true,c=false
var b=Number(a)
var d=Number(c)
document.write(a,typeof a,b,typeof b,d,typeof d)
script>
<script>
var a=null,b=undefined
var c=Number(a)
var d=Number(b)
document.write(c,d)
script>
<script>
var a="123bcd"
var c=parseInt(a)
document.write(c)
script>
注意:严格大小写parseInt
通过*1;/1;-0
<script>
var a=123
var c=a-0
document.write(c,typeof c)
script>
<script>
var a=123
var b=undefined
var c=null
var d=String(a)
var e=String(b)
var f=String(c)
document.write(typeof(d,e,f))
script>
<script>
var a=123
var b=a+"1"
document.write(b)
script>
若双引号内有空格,则值为true
<script>
document.write(1+"2"*3+4)
document.write("1"+"2"*3+4)
script>
!!表示转换为布尔值
短路
var n=10
var m=++n + n++ + ++n
输出结果为m为35,n为13
var n=10;
if(n%2){
document.write("奇数");
}
else{
document.write("偶数");
}
输出结果为 偶数
var n
n=某值
if(n>=90&&n<=100){
document.write("A")
}
else if(n>=80&&n<90){
document.write("B")
}
else if(n>=70&&n<80){
document.write("C")
}
else if(n>=60&&n<70){
document.write("D")
}
else if(n>=0&&n<60){
document.write("E")
}
&&的优先级必||高
<script>
var n
if(n%400==0||(n%4==0&&n%100!=0)){
document.write("闰年")
}
else{
document.write("不是闰年")
}
</script>
break必需写
默认为===,数据类型和值都要一样
<script>
var n=9
switch (n) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
document.write("31天")
break;
case 2:
document.write("28天")
break;
case 4:
case 6:
case 9:
case 11:
document.write("30天")
break;
}
</script>
注意
n=96
m=n/10=9.6
<script>
var n=96;
var m=parseInt(n/10);
switch (m){
case 9:
case 10:
document.write("A")
break;
case 8:
document.write("B")
break;
case 7:
document.write("C")
break;
case 6:
document.write("D")
break;
default:
document.write("E")
break;
}
</script>
<script>
var sum=0
var n=1
while(n<=100){
sum=n+sum
n++
}
document.write(sum)
</script>
<script>
var sum=1
var n=1
while(n<=3){
sum=n*sum
n++
}
document.write(sum)
</script>