1.forEach 会直接改变原数组 不过不会return出去,会遍历整个数组, 例如想根据某个值删除数组中的某一项
var arr = [1,2,3,4,5]
arr.forEach((item, index) => {
if (2 == item) {
arr.splice(0, index)
}
})
这个是根据满足条件的为这个对象添加对应的数据
this.data.siteList.forEach(item => {
if (item.id == 2) {
item.name = '是对接'
}
})
2.every 这个直接改变原数组 我一般是用来给数组对象添加某个属性 将数组对象中的某个值改变 后台返回的时间是时间戳类型的,然后利用这个 代码如下
// 时间戳转年月日时分
function timestampToTimeLine(timestamp) {
// var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y, M, D, h, m;
var date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
Y = date.getFullYear() + '-';
M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
D = change(date.getDate());
h = change(date.getHours()) + ':';
m = change(date.getMinutes());
// s = change(date.getSeconds());
return Y + M + D;
}
res.every(item=>{
item.createTime = this.timestampToTime(new Date(item.createTime));
return true;
})
3.filter 过滤这个会返回新数组 通常根据数组对象中的某个值返回true 或false返回新数组
let arr = _this.data.carList.filter(item => {
return item.id == 2
})
这个是当数组中这个值等于2的时候就返回这个数组对象,这一条数据
let arr = _this.data.carList.filter(item => {
return item.id != 2
})
```这个是返回数组中id值不是2的其他数据
4.map 不会改变新数组 ,map是每遍历一次就会一次值 而不是遍历完数组才会赋值
```javascript
var arr = [10,20,30]
var result = arr.map(function (item,index,array) {
console.log(array[index])
return item+10
})
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => {
if (x == 4) {
return x * 2;
}
});
Array [undefined, 8, undefined, undefined]
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => {
if (x == 4) {
return x * 2;
}
return x;
});