let命令
用let命令限定作用域
变量 i 的作用域
//ES5
if (true) {
var i = 1;
}
console.log(i);
//ES6
if (true) {
let i = 1;
}
console.log(i)
重复定义
var i = 0;
switch (i) {
case 0:
let value = "hello";
case 1:
let value = "world";
}
常量定义
const关键字
const data = 10;
console.log(data);
//data = 100 //执行错误
const list = [10, 20, 30];
console.log(list);
list[0] = 100;
console.log(list);
list = [1, 2, 3];//错误
常量指的是数组本身,而不是数组里每个元素的值!!!
list = [1, 2, 3];//list等于一个新数组,变的是list变量,当然与const定义矛盾
还可插入等
const list = [10, 20, 30];
console.log(list);
list.push(99);
console.log(list);
进制转换
console.log(0b10);//2
console.log(0o10);//8
console.log(0x10);//16
console.log(0b11 === 3);//true
console.log(0o10 === 8);//true
console.log(0x10 === 16);//true
let num = 10;
console.log(num.toString(8));//8进制转化
console.log(num.toString(2));
console.log(num.toString(16));
console.log(num.toString(5));
嵌入字符串
let name = "fmujie"
let mystr1 = "Hello, ${ name }!"
let mystr2 = `Hello, ${ name }! 再见。`
console.log(mystr1)
console.log(mystr2)
function tagged(formats, ...args) {
console.log(formats);
console.log(args);
}
tagged` 你好,${ name }! 再见。` //反单引号
tagged两个参数,一个是格式化的所有的内容,另一个是参数变量所有的值
模板的延长线
标准的模板使用
扩展文字模板
let name = "fmujie"
let address = "公园"
let str = `你好,${ name }! 晚上一起去${ address }玩吧!`
console.log(str)
let fmtstr = markdown`你好,${ name }! 晚上一起去${ address }玩吧!`
console.log(fmtstr)
function markdown(formats, ...args) {
console.log(formats)
console.log(args)
var result = "# 信息标题\n";
for(var i = 0; i< formats.length; i++) {
result += formats[i] + "**" + (args[i] || '') + "**"
}
return result
}
Symbol新类型
let str1 = "Hello World!"
let str2 = "Hello World!"
console.log(str1 == str2)//true
console.log(str1 === str2)//true
let str3 = Symbol("MySymbol")
let str4 = Symbol("Mysymbol")
console.log(typeof str3)
console.log(str3.toString())
console.log(str3 == str4)//false
console.log(str3 === str4)//false
为啥不一样,值虽然一样,但是Symbol内部分配了一个id(哈希值),比较的时候比较的是id值。
Symbol的用法
const Java = Symbol()
const PHP = Symbol()
var lang = PHP
if(lang === PHP) {
console.log("PHP")
}
let str1 = Symbol("mySymbol")
let str2 = Symbol("mySymbol")
var obj = {}
obj[str1] = "Hello"
obj[str2] = "World"
console.log(obj)
console.log(obj[str1])
console.log(obj[str2])
const MyKey = Symbol()
class User {
constructor(key, name, age) {
this[MyKey] = key
this.name = name
this.age = age
}
checkKey(key) {
return this[MyKey] == key;
}
}
let user = new User(123, 'fmujie', 18)
console.log(user.name, user.age, user[MyKey])
console.log(user.checkKey(123))
console.log(user.checkKey(456))
console.log(Object.keys(user))
console.log(JSON.stringify(user))
ES6入门系列说明:本系列仅仅作为ES6入门教学视频的归纳总结与记录,在此感谢小马视频ORYouTube地址
还不快抢沙发