1.反转字符串
const str = 'abcde'
1. [...str].reverse().join('');
2. for 循环倒序
3. [...str].reduce((acc, cur) =>{ return cur + acc}, '');
4. [...str].reduceRight((acc, cur) =>{ return acc + cur}, '');
2.找到页面中所有a标签的href属性
[...document.querySelectorAll('a')].map(item => item.href);
3.有一次面试官问我 map和forEach如何跳出循环
forEach使用throw new Error的方式实现,map也是如此
const arr = [1,2,3,4,5]
try {
arr.forEach((item, index) => {
console.log(item);
if (item === 3) throw new Error("Break");
});
} catch (e) {}
const arr = [1,2,3,4]
try {
arr.map((item, index) => {
console.log(item);
if (item === 3) throw new Error("Break");
});
} catch (e) {}
或者用for of
const array = [1, 2, 3, 4, 5];
for (const element of array) {
console.log(element);
if (element === 3) {
break; // 跳出循环
}
}
Array.find
const array = [1, 2, 3, 4, 5];
array.find((element) => {
console.log(element);
return element === 3; // 返回true时,find会停止循环
});
4.通常我们可以使用for of 结合 break跳出循环,在实际场景,如果符合条件,在跳出循环的同时要终止函数的运行可以使用return来实现
const naNi = ()=>{
let validate = [
"code",
"contractName",
"name"
];
let form = {
code: "123",
contractName: "",
name: "123"
}
for (let e of validate) {
if (form[e] == "") {
console.log('haohaohao')
return;
}
}
console.log('hahahah')
//并不会输出
}
naNi();
这是我之前写的代码,可以使用return代替,删掉多余的代码
5.关于return的问题:先看下下面的代码
//可以单独运行
const naNi = ()=>{
let validate = [
"code",
"contractName",
"name"
];
let form = {
code: "123",
contractName: "",
name: "123"
}
for (let e of validate) {
if (form[e] == "") {
console.log('haohaohao')
return;
}
}
}
naNi();
// 不可以单独运行
let validate = [
"code",
"contractName",
"name"
];
let form = {
code: "123",
contractName: "",
name: "123"
}
for (let e of validate) {
if (form[e] == "") {
console.log('haohaohao')
return;
}
}
//可以单独运行
for(let i = 0;i<10;i++){
console.log(i)
if(i==3){
break;
}
}
//可以单独运行
const array = [1, 2, 3, 4, 5];
for (const element of array) {
console.log(element);
if (element === 3) {
break; // 跳出循环
}
}
看下不可以单独运行的报错信息:
查阅MDN
最原始的for循环也是如此要使用函数包裹才可以使用return,否则要用break来跳出循环,下面是官网示例:
function counter() {
// 无限循环
for (let count = 1; ; count++) {
console.log(`${count}A`); // 直到 5 为止
if (count === 5) {
return;
}
console.log(`${count}B`); // 直到 4 为止
}
console.log(`${count}C`); // 从不出现
}
counter();