一 數組遍歷json
方法一: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);
});spa
總結:map、forEach都是ECMA5新增數組的方法,因此IE9如下瀏覽器還不支持對象
方法四:for-of遍歷字符串
for-of遍歷,ES6新增功能,支持數組、類數組對象、及字符串遍歷,避開for-in循環的缺陷,且可正確響應break,continue和break語句get
for(let item of arr){
console.log(item)it
}
//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);