如果是对数组本身进行操作,则必然要用到for循环,如果是依赖数组做其他东西的操作,则可以用
forEach
最经典的两种操作
1、批量获取数组中的单个元素
let _selectSns = [];
this.multipleSelection.forEach(item => {
_selectSns.push(item.sn);
})
2、对象中为空值时删去该对象里的值
for (const _key in this.params) {
if (this.params[_key] === '') { // 当条件值为''时去除条件
delete this.params[_key];
}
}
for of获取的是键
for in获取的值
数组
1、数组中操作对象(最优)
如果需要对数组中的对象进行操作(相同对象的数量)
可以用arr.forEach(key => {
console.log(key);
})进行遍历
2、数组中操作对象的值
let _selectIds = [];
for (let item of multipleSelection) {
_selectIds.push(item.id);
}
3、数组转化对象
arr.toString();
对象
1、对象转化数组
var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
判断某个值是否为空
if (!item && item !== 0) {
_result = true //值为空
}
2、删除对象里空的键值对
for (const _key in this.params) {
if (this.params[_key] === '') { // 当条件值为''时去除条件
delete this.params[_key];
}
}
最后总结如图: