id = 0
test(data){ if(data.length !=0){ data.forEach(it=>{ it['key'] == this.id; this.id++; it.children = it.list || it.roomList; this.test(it.children); }) } return }
循环之后,key的值都是1,为什么呢?
回答:
看样子 this 是 global 对象,非 strict 模式,浏览器下是这样的环境。测试了,没毛病,只改了两个地方:
it["key"] = this.id
。
如果用==
根本就没赋值,所以可能是原来的值吧。但原来的值是啥我就不知道了。if (data.length != 0)
改为if (data?.length > 0)
在这里:it.children = it.list || it.roomList
,如果这两个属性都不存在,那it.children
就可能是undefined
,这种情况下下面的this.test(it.children)
会出错,因为data.length
会报Cannot read properties of undefined (reading 'length')
。
下面是在 Node 环境下写的一个测试(改过的代码,测试数据来自「树,计算父节点的值」)
const it = { id: 0, test(data) { if (data?.length > 0) { data.forEach(it => { it.key = this.id; this.id++; this.test(it.children); }); } return; } }; const data = [{ "name": "某某公司", "children": [ { "name": "生产序列", "children": [ { "name": "研发部", "children": [{ "name": "软件部" }, { "name": "测试部" }] }, { "name": "工程部", "children": [{ "name": "预算部" }, { "name": "项目管理部" }] } ] }, { "name": "行财序列", "children": [{ "name": "财务部" }, { "name": "办公室" }] } ] }]; it.test(data); console.dir(data, { depth: null });
