js之遍历嵌套数组对象方式
js遍历嵌套数组对象
chuli(arr) {
let kongarr = []
for (let i = 0; i < arr.length; i++) {
console.log("arr[i]", arr[i])
let children1=[]
let children2=[]
let children3=[]
let obj={}
obj.id=arr[i].id
obj.name=arr[i].name
obj.children=children2
let two=arr[i].children
for (let j=0;j<two.length;j++){
console.log("two",two[j])
let san=two[j].children
console.log("san",san)
children2.push({
id:two[j].id,
name:two[j].name,
children:children3
})
if (two[j].name=='市公司'&&two[j].children.length>=2){
let sum=0
for (let k=0;k<san.length;k++){
}
children3.push({
age:"小计"
})
}else {
for (let k=0;k<san.length;k++){
children3.push({
bmdm:san[k].bmdm,
xmlx:san[k].xmlx
})
}
}
}
kongarr.push(obj)
}
console.log("kongarr2", kongarr)
return kongarr
}js中三种主要的遍历对象的方法
for inObject.keysObject.getOwnProperty
对非Array对象类型的遍历
1、for in
主要用于遍历对象的可枚举属性,包括自有属性、继承自原型的属性
var obj = {"name":"tom","sex":"male"};
Object.defineProperty(obj, "age", {value:"18", enumerable:false});//增加不可枚举的属性age
Object.prototype.protoPer1 = function(){console.log("name is tom");};//通过原型链增加属性,为一个函数
Object.prototype.protoPer2 = 2;通过原型链增加属性,为一个整型值2
console.log("For In : ");
for(var a in obj)
console.log(a);输出的截图为:

总结:for in 主要用于遍历对象的可枚举属性,包括自有属性、继承自原型的属性,示例中的属性age为不可可枚举,所以没有输出。
2、Object.keys
此方法返回一个数组,元素均为对象自有可枚举的属性
var obj = {"name":"tom","sex":"male"};
Object.defineProperty(obj, "age", {value:"18", enumerable:false});//增加不可枚举的属性age
Object.prototype.protoPer1 = function(){console.log("name is tom");};//通过原型链增加属性,为一个函数
Object.prototype.protoPer2 = 2;通过原型链增加属性,为一个整型值2
console.log("Object.keys:")
console.log(Object.keys(obj));输出的截图为:

总结:Object.keys主要用于遍历对象自有的可枚举属性,不包括继承自原型的属性和不可枚举的属性。
3、Object.getOwnProperty
此方法用于返回对象的自有属性,包括可枚举和不可枚举的属性
Object.defineProperty(obj, "age", {value:"18", enumerable:false});//增加不可枚举的属性age
Object.prototype.protoPer1 = function(){console.log("name is tom");};//通过原型链增加属性,为一个函数
Object.prototype.protoPer2 = 2;通过原型链增加属性,为一个整型值2
console.log("Object.getOwnPropertyNames: ");
console.log(Object.getOwnPropertyNames(obj));输出的截图为:

总结:Object.getOwnProperty主要用于返回对象的自有属性,包括可枚举和不可枚举的属性,不包括继承自原型的属性。
对Array对象类型的遍历
1、for in
var arr = [1,2,3,4,5,6]; for(var a in arr) console.log(a);
输出的截图为:

总结:输出为数组对象的index 值。
2、Object.keys
var arr = [1,2,3,4,5,6]; console.log(Object.keys(arr));
输出的截图为:

总结:输出为数组对象的index 值。
3、Object.getOwnProperty
var arr = [1,2,3,4,5,6]; console.log(Object.getOwnPropertyNames(arr));
输出的截图为:

总结:输出为数组对象的index 值和数组长度的属性值。
最后
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
layUI使用layer.open,在content打开数据表格,获取值并返回的方法
今天小编就为大家分享一篇layUI使用layer.open,在content打开数据表格,获取值并返回的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-09-09
JS中LocalStorage与SessionStorage五种循序渐进的使用方法
这篇文章主要介绍了JS中LocalStorage与SessionStorage五种循序渐进的使用方法,需要的朋友可以参考下2017-07-07
浅谈JavaScript的innerWidth与innerHeight
下面小编就为大家带来一篇浅谈JavaScript的innerWidth与innerHeight。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-10-10


最新评论