const str = `
<html>
<body>
<div>第一个div<a href="http://17design.cn">一起设计吧</a></div>
<p>这是p</p>
<div>第二个div</div>
<span>第是span</span>
</body>
</html>
`
function selectDiv(regExp, str) {
let matches = []
while(true) {
console.log(regExp.lastIndex)
const match = regExp.exec(str) //子表达式
// console.log(match)
if(match == null) {
break
}
matches.push(match[1])
}
return matches
}
const regExp = /<div>(.*)<\/div>/g
const res = selectDiv(regExp, str)
console.log(res)
console.log(str.match(regExp))
let resR = str.replace(regExp, "一起设计包")
console.log(resR)
function selectDivReplace(regExp, str) {
let matches = []
str.replace(regExp, (all, first)=>{
console.log(all)
matches.push(first)
})
return matches
}
let resReplace = selectDivReplace(regExp, str)
console.log(resReplace)
function selectDivMatch(regExp, str) {
let matches = []
for (let match of str.matchAll(regExp)){
matches.push(match[1])
}
return matches
}
let resReplaceMatch = selectDivMatch(regExp, str)
console.log(resReplaceMatch)
Promise.allSettled([
Promise.resolve({
code:200,
data:[1, 3, 4]
}),
Promise.reject({
code:500,
data:[]
}),
Promise.resolve({
code:200,
data:[1, 2, 3]
})
]).then(res =>{
console.log("成功")
console.log(res)
}).catch(err =>{
console.log(err)
})
// 全局对象:globalThis
const getGlobal = () => {
if(typeof self !== "undefined"){
return self
}if(typeof window !== "undefined"){
return window
}if(typeof global !== "undefined") {
return global
}
throw new Error("无法找到全局对象")
}
const global = getGlobal()
console.log(global)
console.log(globalThis)
//可选链:Optional chaining
const user = {
address: {
street: "某某街道",
getNum() {
return "80号"
}
}
}
// const street = user && user.address && user.address.street
const street = user?.address?.street //es2020可选链
console.log(street)
const b = (null && undefined)
console.log(b)
const a = b ?? 6 //只有前面的是null 和 undefined 才会取默认值 6
console.log(a)
一起设计吧