Vue中foreach/map/filter的使用及说明
作者:仰.
foreach、map和filter是JavaScript中用于数组操作的三个方法,foreach用于循环遍历数组并对每个元素进行操作,不会改变原数组,没有返回值,map也用于遍历数组,但会返回一个新的数组,不会改变原数组,每次遍历都有返回值,filter用于过滤数组,根据条件返回一个新的数组
1.foreach—用来循环遍历数组
(会改变原数组,可以对每一个数据进行同一个操作没有返回值)不能直接循环数组包含对象。
<script>
export default {
data() {
return {
Array: [1, 2, 3, 4, 5, 6],
};
},
mounted() {
let arr = [];
this.Array.forEach((item, index, Array) => {
// console.log(arrayTest);
console.log(item + "-" + index + "-" + Array);
arr.push(item);
});
console.log(arr); //(6) [1, 2, 3, 4, 5, 6]0: 11: 22: 33: 44: 55: 6length: 6[[Prototype]]: Array(0)
},
};
</script>
2.map ——循环遍历数组
(会返回一个新的数组,不会改变原数组,每一次遍历都会有返回值,最后所有的返回值组合成为最终的结果)可以循环数组包含对象。其中三个参数也是(元素,下标,原数组)。
<script>
export default {
data() {
return {
Array: [1, 2, 3, 4, 5, 6],
};
},
mounted() {
let arrayTest = this.Array.map((item, index, array) => {
return item - 1 + "-" + index + "-" + array;
});
console.log(arrayTest);
let arrayTest2 = this.arrayObject.map((item) => {
return item;
});
console.log(arrayTest2);
},
};
</script>
3.filter是用来过滤筛选的。(有返回值)
<script>
export default {
data() {
return {
Array: [1, 2, 3, 4, 5, 6],
arrayObject: [
{ name: "zhangsan", age: "19" },
{ name: "lisi", age: "20" },
],
};
},
mounted() {
let result = this.Array.filter((item) => {
return item > 2;
});
console.log(result);//3、4、5、6
},
};
</script>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
