forEach 循环无法自增变量的问题?

2023-03-22 0 726

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 模式,浏览器下是这样的环境。测试了,没毛病,只改了两个地方:

  1. it["key"] = this.id
    如果用 == 根本就没赋值,所以可能是原来的值吧。但原来的值是啥我就不知道了。
  2. 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 });
forEach 循环无法自增变量的问题?
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 forEach 循环无法自增变量的问题? https://www.jkxiazai.com/842.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务