判断字符串中括号使用是否规范
function isValid(str) {
function removeDouble(str) {
let startLength = str.length
str = str.replace(/\(\)|\[\]|\{\}/, '') // 去除()[]{}
let endLength = str.length
if (startLength === endLength) { // 去除括号前后长度一致说明不符合规则
return false
}
if(str.length > 0) {
return removeDouble(str)
} else {
return true
}
}
return str.length % 2 !== 0 ? false : removeDouble(str)
}
console.log(isValid('()[({})]{}')) // true
console.log(isValid('()([{})]{}')) // true
隐式转换问题
console.log(1 + "2" + "2");
console.log(1 + +"2" + "2"); // 相当于 1 + 0+"2" + "2" Unary plus (+)
console.log(1 + -"1" + "2");
console.log(+"1" + "1" + "2");
console.log( "A" - "B" + "2");
console.log( "A" - "B" + 2);
手写flat
function flat(arr) {
if (arr.length <= 1) {
return arr
}
let result = []
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'object') {
result = result.concat((flat(arr[i])))
} else {
result.push(arr[i])
}
}
return result
}
宏微任务
console.log(1);
const promise = new Promise((resolve) => {
console.log(2);
resolve();
console.log(3);
});
async function foo() {
console.log(4);
await promise;
console.log(6);
}
foo();
promise.then(() => {
console.log(7);
});
setTimeout(() => console.log(8));
console.log(5);
判断数据类型
function foo() {
let a = b = 0;
a++;
return a;
}
foo();
typeof a; // => ???
typeof b; // => ???
###遍历都没 遍历元素可以使用以下几种不同的实现方法:
使用for循环遍历元素:
var elements = document.getElementsByClassName("example");
for(var i=0; i<elements.length; i++) {
console.log(elements[i]);
}
这种方法使用一个for循环来遍历元素集合,并使用索引(i)进行访问。
使用forEach方法遍历元素:
var elements = document.getElementsByClassName("example");
Array.prototype.forEach.call(elements, function(element) {
console.log(element);
});
这种方法将类数组对象转换为真正的数组,然后使用forEach方法来遍历元素。
使用ES6的for...of循环遍历元素:
var elements = document.getElementsByClassName("example");
for(var element of elements) {
console.log(element);
}
这种方法使用ES6的for...of循环来遍历元素集合。
请注意,上述所有方法的前提是有一个具体的类名或其他属性用于选择元素集合。根据具体情况,可能需要使用其他DOM选择器方法来获取元素集合。
或者
var elements = document.getElementsByClassName("example")
elements = [...elements]
elements.forEach