一、map方法 (返回一个新的数组 新数组中的元素是经过map函数内部代码块处理过的数据)
testMap() {
		let array = [1, 2, 3, 4];
		let newArray = array.map(item=>{
		return item += 1;
		});
		console.log(newArray);
	}注意点:map函数内部必须要有return 将数据返回 否则默认返回 undefinedtestFilter() {
		let array = [1, 2, 3, 4];
		let newArray = array.filter(item=>{
		return item > 2 ;
		});
		console.log(newArray);
}testForEach() {
		let array = [1, 2, 3, 4];
		let newArray = [];
		array.forEach(item => {
		newArray.push(item+1);
		});
		console.log(newArray );
}注意 改变item值 并不会改变原数组中的元素值testForEach() {
		let array = [1, 2, 3, 4];
		array.forEach(item => {
		item = item +1;
		});
		console.log(array);//1,2,3,4
}并且forEach函数内 不支持 continue 和 break 操作 (普通for 循环支持这两个操作)testForEach() {
		let array = [1, 2, 3, 4];
		let newArray = [];
		array.forEach(item => {
		if(item ===2 ){
		return;
		}
		newArray.push(item);
		});
		console.log(newArray);//1,3,4
} testFindAndFindIndex() {
	let array = [1, 2, 3, 4];
	
	let item1 = array.find(item=> item > 3);
	console.log(item1);
	
	let index1 = array.findIndex(item=> item > 3);
	console.log(index1);
	
	let item2 = array.find(item=> item > 4);
	console.log(item2);
	
	let index2 = array.findIndex(item=> item > 4);
	console.log(index2);
}结果: 
 testSomeAndEvery() {
	let array = [1, 2, 3, 4];
	
	let flagSome = array.some(item=> item > 3);
	console.log(flagSome);
	
	let indexEvery = array.every(item=> item > 3);
	console.log(indexEvery);
}结果: 
 // 使用 reduce
<template>
<div class="index">
<h1 ref="myh1"> App 组件 </h1>
<!-- <LeftModal ref="left"></LeftModal> -->
<span>总价:{{ total }}</span>
<br>
<el-button @click="handleFind">计算</el-button>
</div>
</template>
<script>
export default {
data(){
return {
arr: [
{id: 1, name: "西瓜", state: true, price: 10, count: 1},
{id: 2, name: "榴莲", state: true, price: 80, count: 2},
{id: 3, name: "草莓", state: true, price: 30, count: 3},
],
state: '',
total: 0,
}
},
methods:{
handleFind(){
// 计算 state = true 的总价格
// this.arr.filter(item=>item.state) // 过滤出 state 为 true 的数据
// let xxx = this.arr.filter(item=>item.state).reduce((累加的结果, 当前循环项) => { ...., return 处理结果 }, 初始值)
this.total = this.arr.filter(item=>item.state).reduce((total, item ) => {
return total += item.price * item.count
}, 0)
}
}
}
</script>
- 本文标题: JSON常用属性,some,every,map,foreach,map,求和等
- 文章分类:【VueJS】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.