1. 知识点
2. 复习
let和const命令
let 定义的变量不能被提升, let的作用域是一个块,不能重复被声明, const修饰的变量不能被更改,但是变量对象里面的属性可以被修改
for循环经典案列,输出是10
ini
<script>
var arr = [];
for (i = 0; i < 10; i++) {
arr[i] = function () {
return i;
};
}
console.log(arr[5]());
</script>
let 不会污染全局变量
xml
<script>
let Regexp = 10;
console.log(Regexp);
console.log(window.RegExp);
</script>
模板字符串
使用反引号插入变量的时候使用${}
ini
<script>
let id = "test1";
let name = "roy";
const innerHtml = `<ul>
<li>
<p id=${id}>${name}</p>
</li>
</ul>`;
const box = document.querySelector(".test");
box.innerHTML = "<ul><li><p id = " + id + ">" + name + "</p></li></ul>";
box.innerHTML = innerHtml;
</script>
函数带默认值、剩余参数
xml
<script>
//默认传参是一个表达式
function add(a, b = getVal(5)){
return a + b;
}
function getVal(val){
return val + 10;
}
console.log(add(10));
</script>
ini
<script>
let book = {
name: "听说你喜欢我",
author: "roy",
year: 2023,
};
let result = pick(book, "author", "year");
function pick(obj, ...keys) {
let result = Object.create(null);
for (let i = 0; i < keys.length; i++) {
result[keys[i]] = obj[keys[i]];
}
return result;
}
console.log(result);
</script>
函数带默认值、剩余参数
箭头函数没有this指向,箭头函数内部this值只能通过查找作用域链来确定, init不能采用箭头函数,不然this就是window了,使用箭头函数,函数内部没有arguments
箭头函数不能使用new关键字实例化对象,function函数也是一个对象,但箭头函数不是一个对象,只是一个语法糖
xml
<script>
const arr = [13, 243, 45, 23];
console.log(Math.max(...arr));
</script>
xml
<script>
let pageHandle = {
id: 123,
init: function () {
document.addEventListener(
"click",
(event) => {
this.doSomeThing(event.type);
},
false
);
},
doSomeThing: function (type) {
console.log(`事件类型:${type},当前id:${this.id}`);
},
};
pageHandle.init();
</script>
解构赋值
xml
<script>
//不完全解构,可以对对象和数组进行解构
let obj = {
a: {
name: "roy",
},
b: [],
c: "hello world",
};
let { a, ...res } = obj;
console.log(res);
console.log(a);
</script>
xml
<script>
//is 严格对比两个对象是否相等
console.log(Object.is(NaN, NaN));
//对象合并
var obj = Object.assign({}, { a: 1 }, { b: 2 });
console.log(obj);
</script>
Symbol 的使用
xml
<script>
//原始数据类型Symbol,表示独一无二的值
//最大的用途是用来定义对象的私有变量
const name = Symbol('name');
const name2 = Symbol('name');
//false
console.log(name === name2);
</script>
Set 的用法
xml
<script>
let set = new Set();
set.add("2");
set.add("3");
set.add(["heloo", "world", "4"]);
set.delete("5");
console.log(set.has("2"));
console.log(set.size);
set.forEach((val, key) => {
//value和key相等
console.log(val);
console.log(key);
});
//set换转成数组,实现数组去重
let set2 = new set([1, 2, 4, 4, 3]);
let arr = [...set2];
console.log(arr);
</script>
数组操作
xml
<script>
//from,将伪数组转换成真正的数组
function add() {
let arr = Array.from(arguments);
console.log(arr);
}
add(1, 2, 3);
let lis = document.querySelectorAll("li");
console.log(Array.from(lis));
//扩展运算符转换成真正的数组
console.log([...lis]);
//from可以接受第二个参数,用于处理每个元素
let liConetnt = Array.from(lis, (ele) => ele.textContent);
console.log(liConetnt);
//of 可以将任意的数据类型转换成数组
console.log(Array.of(3, 12, 34, [1, 34, 34]));
</script>
Promise操作
对象的状态不受外部影响,处理异步操作三个状态,pending进行中、resolved 成功, rejected失败
一但状态改变,就不会再变吗,任何时候都可以得到这个结果
xml
<script>
let promise = new Promise(function (resolved, rejected) {
//执行异步操作
let res = {
code: 201,
data: {
name: "roy",
},
error: {
info: "shibai",
},
};
setTimeout(() => {
if (res.code === 200) {
resolved(res.data);
} else {
rejected(res.error);
}
}, 5000);
});
console.log(promise);
promise.then(
(val) => {
console.log(val);
},
(error) => {
console.log(error);
}
);
function timeOut(ms) {
return new Promise((resolved, rejected) => {
setTimeout(() => {
resolved("hello promise return");
}, ms);
});
}
timeOut(2000).then(
(val) => {
console.log(val);
},
(error) => {
console.log(error);
}
);
</script>
xml
<script>
const getJSON = function (url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = handler;
xhr.responseType = "json";
xhr.setRequestHeader("Accept", "application/json");
xhr.send();
function handler() {
console.log(this.readyState);
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
}
});
};
getJSON(
"https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976"
).then(
(res) => {
console.log(res);
},
function (error) {
console.error(error);
}
);
</script>
xml
<script>
function requestImg(imgSrc) {
return new Promise((resolve, reject) => {
var img = new Image();
img.onload = function () {
resolve(img);
};
img.src = imgSrc;
});
}
//延时函数,用于给请求计时
function timeout() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject("图片请求超时");
}, 5000);
});
}
Promise.race([requestImg("./3.gif"), timeout()])
.then((data) => {
console.log(data);
document.body.appendChild(data);
})
.catch((err) => {
console.log(err);
});
</script>
async\await的用法
xml
<script>
async function f2() {
throw new Error("error....");
}
f2()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
</script>
xml
<script>
//如果async 函数中有多个await,那么then函数会等待所有的await指令
//使得异步操作更加方便,async会返回一个Promise对象
async function f2() {
//throw new Error("error....");
try {
await Promise.reject("error....");
} catch (error) {
return Promise.resolve("hello");
}
}
f2()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
</script>