一 数组遍历
方法一:for循环
方法二:forEach遍历
forEach遍历数组 性能低于for循环,且不可使用break中断循环,也不能使用return返回外层函数
arr.forEach(function(item,index){
console.log("forEach遍历",index,item);
});
方法三:map遍历
map遍历 支持return返回
arr.map(function(item,index){
console.log("forEach遍历",index,item);
});
总结:map、forEach都是ECMA5新增数组的方法,所以IE9以下浏览器还不支持
方法四:for-of遍历
for-of遍历,ES6新增功能,支持数组、类数组对象、及字符串遍历,避开for-in循环的缺陷,且可正确响应break,continue和break语句
for(let item of arr){
console.log(item)
}
//hasOwnProperty 判断当前json对象item中是否包含某个属性key
if(item.hasOwnProperty(value)){
console.log(value);
}
方法五:find 遍历数组、json对象
arr.find(function(item){
console.log(item[key2]);
})
实例:获取接送对象里的某个属性值
let jsonObj = [{id:3,name:"张三"},{id:2,name:"yali"}];
function jsonKey(obj,key,value,key2){
let _value = '';
obj.find(function(item){
if(item[key] && item[key]==value){
_value = item[key2];
}
})
return _value;
}
var getVal = jsonKey(jsonObj,'name',"张三",'id')
console.log(getVal);