表达式与语句
表达式
- 1+2 表达式的值为 3
- add(1,2) 表达式的值为函数的返回值
- console.log 表达式的值为函数本身
- console.log(3) 表达式的值为 undefined
语句
- var a = 1 是一个语句
二者的区别
- 表达式一般都有值,语句可能有也可能没有
- 语句一般改变环境(声明、赋值)
- 上面两句话并不是绝对的
标识符
规则
- 第一个字符,可以是 Unicode 字母或者 $ 或 _ 或中文
- 后面的字符,除了上面所说,还可以有数字
变量名是标识符
var _ = 1
var $ = 2
var ______ = 6
var 你好 = 'hi'
if 语句
语法
- if (表达式) {语句1} else {语句2}
- {} 在语句只有一句的时候可以省略,不建议这样做
变态情况
- 表达式里可以非常变态,如 a = 1
a = 2
if (a = 1) {
console.log('a是1')
} else {
console.log('a不是1')
}
// 输出结果:a是1
a = 2
if (a ===1) {
console.log('a是1')
} else {
console.log('a不是1')
}
// 输出结果:a不是1
a = 2
if (1 = a) {
console.log('a是1')
} else {
console.log('a不是1')
}
// 报错结果:Uncaught ReferenceError: Invalid left-hand side in assignment
- 语句1里可以非常变态,如嵌套的 if else
a = 2
if (a === 1) {
if (a > 9) {
}
}
// 输出结果:undefined
a = 2
if (a < 100)
if ( a < 10)
console.log('a小于10')
// 输出结果:a小于10
- 语句2里可以非常变态,如嵌套的 if else
if (a < 100) {
} else {
if (a > 10000) {
console.log('a大于10000')
}
}
// 等价于
if (a < 100) {
} else if (a > 10000) {
console.log('a大于10000')
}
- 缩进也可以很变态,如面试题常常下套
a = 1
if (a === 2)
console.log('a')
console.log('a等于2')
// 输出结果:a等于2
a = 1
if (a === 2)
console.log('a'); console.log('a等于2')
// 输出结果:a等于2
a = 1
if (a === 2)
console.log('a'), console.log('a等于2')
// 输出结果:undefined
最推荐使用的写法
使用最没用歧义的写法
if (表达式) {
语句
} else if (表达式) {
语句
} else {
语句
}
次推荐使用的写法
function fn(){
if (表达式) {
return 表达式
}
if (表达式) {
return 表达式
}
return 表达式
}
while
语法
- while (表达式) {语句}
- 判断表达式的真假
- 当表达式为真,执行语句,执行完再判断表达式的真假
- 当表达式为假,执行后面的语句
其他
- do...while 用得不多,自行了解
var i = 0
while (i < 10){
console.log(i)
i = i + 1
}
// log 输出 1~9,最后全局的 i 为 10
var a = 0.1
while (a !== 1){
console.log(a)
a = a + 0.1
}
// 浮点数加着加着就不精确了。永远不等于 1,死循环
for 循环
语法糖
- for 是 while 循环的方便写法
语法
for(语句1;表达式2;语句3){
循环体
}
- 先执行语句1
- 然后判断表达式2
- 如果为真,执行循环体,然后这姓语句3
- 如果为假,直接退出循环,执行后面的语句
for(let i = 0; i < 5; i++){
console.log(i)
}
// log 输出 0~4
// 终端输入 i, 报错信息:
// ReferenceError: i is not defined
for(var i = 0; i < 5; i++){
console.log(i)
}
// log 输出 0~4
// 终端输入 i, 结果为 5
for(var i = 0; i < 5; i++){
setTimeout(()=>{
console.log(i + '随机数' + Math.random())
}, 0)
}
// 因为 setTimeout 等一会才执行
// 输出结果是:5行
// 5随机数Math.random()产生的随机数数字
// 执行5遍,类似于你设置5个闹钟
break 和 continue
退出所有循环 V.S. 退出当前一次循环
for(var i = 0; i < 10; i++){
if(i%2 === 1){
break
}
}
// i 为 0 的时候就退出了循环,最后全局 i 为 1
for(var i = 0; i < 10; i++){
if(i%2===1){
continue
}else{
console.log(i)
}
}
// log 输出 0 2 4 6 8
for(var i = 0; i < 10; i++){
for(var j = 101; j < 110; j++){
if(i === 5){
break
}
}
console.log(i)
}
// log 输出 0 ~ 9
// break 只会退出离他最近的 for 循环
label
语法
foo: {
console.log(1);
break foo;
console.log('本行不会输出');
}
console.log(2)
foo: {
console.log(1);
break foo;
console.log('本行不会输出');
}
console.log(2)
// 输出 1 和 2
foo: 1
console.log(2);
// 终端输出 2
{
foo: 1
console.log(2);
}
// 终端输出 2
{
foo: 1
}
// 在 Firefox 是代码块,在 chrome 优化成对象。