看代码输出
let a = { x: 1 },
ref = a;
a.x = a = { h: 1 };
console.log(a, ref);
{h:1}, {x:{h:1}}
.优先级更高,所以先执行a.x=a,ref = {x:a},- 接着执行
a={h:1},由于引用类型,ref变成{x:{h:1}}
看代码输出
setTimeout(() => {
console.log(1);
}, 0);
console.log(2);
new Promise((resolve, reject) => {
console.log(3);
setTimeout(resolve, 1000);
}).then(() => {
console.log(4);
});
2,3,1,4
大写驼峰转下划线
如 HelloWorld转成 hello_world
// 使用 replace
function underlineWord(str) {
if (typeof str !== "string") {
throw new Error("type Error!");
}
let newStr = str.replace(/[A-Z]/g, (pre, index) => {
if (index === 0) return pre.toLowerCase();
return "_" + pre.toLowerCase();
});
return newStr;
}
let str = "HelloWorld";
console.log(underlineWord(str));
字符串匹配-有效括号
// 使用栈
function isLegal(str) {
if (typeof str !== "string") {
throw new Error("type Error!");
}
let arr = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === "{" || str[i] === "[" || str[i] === "(") {
arr.push(str[i]);
} else if (
(str[i] === "}" && arr.at(-1) === "{") ||
(str[i] === ")" && arr.at(-1) === "(") ||
(str[i] === "]" && arr.at(-1) === "[")
) {
arr.pop();
continue;
} else {
return false;
}
}
return arr.length === 0;
}
console.log(isLegal("{}[]()")); // true
事件代理
点击p标签时,输出对应p标签的内容和data-index
<div id="box">
<p data-index="a">1</p>
<p data-index="b">2</p>
<p data-index="c">3</p>
<div>4</div>
</div>
let dom = document.getElementById("box");
dom.addEventListener("click", (e) => {
let tar = e.target;
if (tar.nodeName.toLowerCase() === "p") {
// 内容
console.log(tar.innerHTML);
console.log(tar.dataset.index);
}
});