foreach map filter区别
1、三者都不会改变原数组,但map 和filter会返回一个新数组。也就是map filter有返回值。
2、foreach 和map 用法类似
foreach
const array1 = ['a', 'b', 'c'];
array1.forEach((element) => console.log(element));
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
Array.prototype.forEach(item,index,array)array:数组本身
没有返回值、不能中止或跳出 forEach 循环、使用箭头函数时this
会被忽略变为window
map
用法和foreach类似
const array1 = [1, 4, 9, 16];
// Pass a function to map
const map1 = array1.map((x) => x * 2);
console.log(map1);
// Expected output: Array [2, 8, 18, 32]
filter用法
过滤使用,为数组中的每个元素执行的函数。它应该返回一个真值以将元素保留在结果数组中,否则返回一个假值
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
forof 获取下标
结果:
Object.entries() mdn链接
Object.entries()
静态方法返回一个数组,包含给定对象自有的可枚举字符串键属性的键值对。