变量 let
- 块级作用域内有效
- 不能重复声明
- 不会预处理,不存在提升
var btns = document.getElementsByTagName('button');
for (let i = 0; i < btns.length; i++) {
var btn = btns[i];
btn.onclick = function(){
alert(i)
}
}
// for (var i = 0; i < btns.length; i++) {
// var btn = btns[i];
// (function(i){
// btn.onclick = function(){
// alert(i)
// }
// })(i)
// }
常量 const const key = 'Kevin'
解构赋值
//解构对象
let obj = {username: 'Tom', age: 20}
let {username, age} = obj;
console.log(username, age); //Tom 20
//解构数组
let arr = [20, 'ab', 'Tom']
let [,a,b] = arr;
console.log(a, b); //ab Tom
//多形参解构
function person({username, age}){
console.log(username, age);
}
var p1 = {username: 'Kevin', age:28}
person(p1); //Kevin 28
模板字符串
let name = 'Kevin';
let str = `Hello Es6 String, I am ${name}.`;
console.log(str); //Hello Es6 String, I am Kevin.
对象简写
let username = 'Kevin';
let age = 28;
//省略同名属性
//省略方法function
let person = {
username,
age,
getUserName() {
return this.username;
}
}
console.log(person); //{username: 'Kevin', age: 28, getUserName: f..}
console.log(person.getUserName()); //Kevin
箭头函数
//作用:定义匿名函数
let fun1 = () => console.log('fun1');
//一个形参时可省略括号;函数体无大括号时自动return结果
let fun2 = x => x*2;
//多个形参;函数体有大括号时不自动返回结果
let fun3 = (x, y) => x + y;
let fun4 = (x, y) => {
console.log(x, y);
return x + y;
}
//箭头函数没有自己的this,不是调用时候决定的,而是定义时候的所处对象
//技巧: 看this外层是否有函数
//1. 有:外层函数的this就是内部箭头函数的this
//2. 无:this指向window
let user = {
name: 'Kevin',
getUser: function(){
console.log(this); //{name: "Kevin", getUser: ƒ}
}
}
user.getUser(); //Kevin
let user2 = {
name: 'Tom',
getUser: () => {
console.log(this);
}
}
user2.getUser(); //window
三点运算符
//可变参数
function fun1(...values){
console.log(arguments); //["a", "b", "c", callee: (...), Symbol(Symbol.iterator): ƒ]
console.log(...arguments); //a b c
console.log(values); //["a", "b", "c"]
let args = Array.prototype.slice.call(arguments);
console.log(args); //["a", "b", "c"]
}
fun1('a', 'b', 'c');
//扩展运算
let arr1 = [3,4,5];
let arr2 = [1,2,...arr1,6];
console.log(arr2); //[1, 2, 3, 4, 5, 6]
形参默认值
function Point(x = 0, y = 0){
this.x = x;
this.y = y;
}
let point = new Point();
console.log(point.x, point.y); // 0 0
Promise
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('yes');
// reject('no');
}, 1000)
})
promise
.then((data) => {
console.log(data); //yes
}, (error) => {
console.log(error); //no
})
//定义一个Get请求的方法
function sendGetAjax(url){
//创建一个promise对象
let promise = new Promise((resolve, reject) => {
//初始化promise状态为pending
//启动异步任务
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if(request.readyState === 4){
if(request.status === 200){
let data = request.response;
resolve(data);
}else{
reject('error');
}
}
};
request.responseType = 'json';//设置返回的数据类型
request.open("GET", url);//规定请求的方法,创建链接
request.send();//发送
})
return promise;
}
Iterator
- iterator是一种接口机制,为各种不同的数据结构提供统一的访问机制
//迭代器原理
function mockInterator(arr){
var nextIndex = 0;
return {
next: function(){
return (nextIndex < arr.length) ? {value: arr[nextIndex++], done: false} : {value: undefined, done:true}
}
}
}
let arr = [1,2,3,'abc'];
let obj = mockInterator(arr)
console.log(obj.next()); //{value: 1, done: false}
console.log(obj.next()); //{value: 2, done: false}
console.log(obj.next()); //{value: 3, done: false}
console.log(obj.next()); //{value: "abc", done: false}
console.log(obj.next()); //{value: undefined, done: true}
console.log(obj.next()); //{value: undefined, done: true}
// 原生具备iterator接口的数据(可用for of遍历)
// 1、Array
let arr3 = [1, 2, 'kobe', true];
for(let i of arr3){
console.log(i);
}
// 2、arguments
// 3、set容器
// 4、map容器
// 5、String
let str = 'abcdefg';
for(let item of str){
console.log(item);
}
Generator
function* sendXml() {
// url为next传参进来的数据
let url = yield getNews('http://localhost:3000/news?newsId=2');
yield getNews(url);
}
function getNews(url) {
$.get(url, function (data) {
console.log(data);
let commentsUrl = data.commentsUrl;
let url = 'http://localhost:3000' + commentsUrl;
// 当获取新闻内容成功,发送请求获取对应的评论内容
// 调用next传参会作为上次暂停是yield的返回值
sx.next(url);
})
}
let sx = sendXml();
// 发送请求获取新闻内容
sx.next();
Async
async function sendXML(url) {
return new Promise((resolve, reject) => {
$.ajax({
method: 'GET',
url,
success: data => resolve(data),
error: error => reject(error)
})
})
}
async function getNews(url){
let result = await sendXML(url);
console.log('->', result);
result = await sendXML(url + result.commentId);
console.log('->', result);
}
getNews('http://localhost:30001/news?id=9');
Class
class Person {
//调用类的构造方法
constructor(name, age){
this.name = name;
this.age = age;
}
//定义一般的方法
showName(){
console.log(this.name, this.age);
}
}
let person = new Person('kobe', 39);
console.log(person, person.showName());
//定义一个子类
class StrPerson extends Person{
constructor(name, age, salary){
super(name, age);//调用父类的构造方法
this.salary = salary;
}
showName(){//在子类自身定义方法
console.log(this.name, this.age, this.salary);
}
}
let str = new StrPerson('weide', 38, 1000000000);
console.log(str);
str.showName();
扩展
字符串扩展
- includes(str) : 判断是否包含指定的字符串
- startsWith(str) : 判断是否以指定字符串开头
- endsWith(str) : 判断是否以指定字符串结尾
- repeat(count) : 重复指定次数
let str = "Asjodifjasoid";
console.log(str.includes("a")); //true
console.log(str.startsWith("b")); //false
console.log(str.endsWith("d")); //true
let str2 = str.repeat(2);
console.log(str2); //AsjodifjasoidAsjodifjasoid
数值拓展
- 二进制与八进制数值表示法: 二进制用0b, 八进制用0o
- Number.isFinite(i) : 判断是否是有限大的数
- Number.isNaN(i) : 判断是否是NaN
- Number.isInteger(i) : 判断是否是整数
- Number.parseInt(str) : 将字符串转换为对应的数值
- Math.trunc(i) : 直接去除小数部分
console.log(0b1000); //8
console.log(Number.isFinite(5)); //true
console.log(Number.isNaN(NaN)); //true
console.log(Number.isInteger(1.1)); //false
console.log(Number.parseInt('123abc')); //123
console.log(Math.trunc(11.123)); //11
数组拓展
//Array.from(v) : 将伪数组对象或可遍历对象转换为真数组
let btns = document.getElementsByTagName('button');
console.log(btns.length);//3
Array.from(btns).forEach(function (item, index) {
console.log(item, index);
});
//Array.of(v1, v2, v3) : 将一系列值转换成数组
let arr = Array.of(1, 'abc', true);
console.log(arr);
//find(function(value, index, arr){return true}) : 找出第一个满足条件返回true的元素
let arr1 = [1,3,5,2,6,7,3];
let result = arr1.find(function (item, index) {
return item >3
});
console.log(result);//5
//findIndex(function(value, index, arr){return true}) : 找出第一个满足条件返回true的元素下标
let result1 = arr1.findIndex(function (item, index) {
return item >3
});
console.log(result1);//2
对象扩展
console.log(Object.is('abc', 'abc'));//true
console.log(NaN == NaN);//false
console.log(Object.is(NaN, NaN));//true
console.log(0 == -0);//true
console.log(Object.is(0, -0));//false
//Object.assign(target, source1, source2..) 浅拷贝
let obj = {name : 'kobe', age : 39, c: {d: 2}};
let obj1 = {};
Object.assign(obj1, obj);
console.log(obj1, obj1.name);
//直接操作 __proto__ 属性
let obj3 = {name : 'anverson', age : 41};
let obj4 = {};
obj4.__proto__ = obj3;
console.log(obj4, obj4.name, obj4.age);
深度克隆
function objDeepCopy(obj) {
var result = Array.isArray(obj) ? [] : {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object') {
result[key] = objDeepCopy(obj[key]); // 递归复制
} else {
result[key] = obj[key];
}
}
}
return result;
}