JS 常用遍历方法&高阶函数
关于JS的一些总结, 持续更新中……
1.for()
最常用的for
循环,经常用的数组遍历,也可以遍历字符串。
const arr = [1, 2, 3];
const str = "abc";
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
console.log(str[i]);
}
2.while() / do while()
while
、do while
主要的功能是,当满足while
后边所跟的条件时,来执行相关业务。这两个的区别是,while
会先判断是否满足条件,然后再去执行花括号里面的任务,而do while
则是先执行一次花括号中的任务,再去执行while
条件,判断下次还是否再去执行do
里面的操作。也就是说 **do while**
至少会执行一次操作.
while(条件){
执行...
}
------------
do{
执行...
}
while(条件)
3.forEach()
拷贝一份遍历原数组。
return
无法终止循环。不过可以起到continue
效果。- 本身是不支持的
continue
与break
语句的我们可以通过some
和every
来实现。
const arr = [5, 1, 3, 7, 4];
arr.forEach((item, index) => {
if (item < 2) return;
console.log(`索引:${index},数值:${item}`);
arr[5] = 0;
});
console.log(arr);
// 打印结果:
// 索引:0,数值:5
// 索引:2,数值:3
// 索引:3,数值:7
// 索引:4,数值:4
// [5, 1, 3, 7, 4, 0]
4.for...in
for...in
是 ES5 标准, 此方法遍历数组效率低,主要是用来循环遍历对象的属性。- 遍历数组的缺点:数组的下标
index
值是数字,for-in
遍历的index
值"0","1","2"
等是字符串。 Object.defineProperty
,建立的属性,默认不可枚举。
const foo = {
name: "bar",
sex: "male",
};
Object.defineProperty(foo, "age", { value: 18 });
for (const key in foo) {
console.log(`可枚举属性:${key}`);
}
console.log(`age属性:${foo.age}`);
// 打印结果:
// 可枚举属性:name
// 可枚举属性:sex
// age属性:18
5.for...of
for…of
是ES6
新增的方法,但是for…of
不能去遍历普通的对象,**for…of**
的好处是可以使用**break**
跳出循环。
for-of
这个方法避开了for-in
循环的所有缺陷- 与
forEach()
不同的是,它可以正确响应break
、continue
和return
语句 for-of
循环不仅支持数组,还支持大多数类数组对象,例如DOM
NodeList 对象[6]。-
for-of
循环也支持字符串遍历
// for of 循环直接得到的就是值
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value);
}
面试官:说一下 **for...in**
和 **for...of**
区别?
(1)for