首页 > 解决方案 > 在 JavaScript 中推送后没有改变数组的长度

问题描述

请帮助我解决奇怪的行为。我声明了一个数组: buildsArray = new Array();

并像这样在数组中添加对象项:

  var detailBuild = {
              id: elements.data.id,
              username: (elements.data.triggered.user) ? elements.data.triggered.user.username : "not user",
              project: (elements.data.buildType) ? elements.data.buildType.projectName : "not project",
              status: elements.data.status
            };
            buildsArray.push(detailBuild);

但是推送之后,我的数组的长度属性等于0。虽然

console.log (buildsArray);
console.log ("the length of buildsArray is " + buildsArray.length);

给我看这个: 在此处输入图像描述

请告诉我我做错了什么,谢谢

完整代码:

 return promise.then((elements) => {
        console.log (elements.data.build);
        elements.data.build.forEach(element => {

          var detailpromise = httpService.getBuildDetail(element.href);
          detailpromise.then((elements) => {

            var detailBuild = {
              id: elements.data.id,
              username: (elements.data.triggered.user) ? elements.data.triggered.user.username : "not user",
              project: (elements.data.buildType) ? elements.data.buildType.projectName : "not project",
              status: elements.data.status
            };
            buildsArray.push(detailBuild);
            var item = buildsGroupingByProject.find(element => element.projectName === detailBuild.project);
            (item === undefined) ?
            buildsGroupingByProject.push({
                projectName: detailBuild.project,
                buildArrays: new Array(detailBuild)
              })
              :
              item.buildArrays.push(detailBuild);

          });
        });
        console.log (buildsArray);
        console.log ("the length of buildsArray is " + buildsArray.length);
        return buildsGroupingByProject;
      });
    }

标签: javascriptarrays

解决方案


推荐阅读