简体   繁体   English

JavaScript数组推送不起作用

[英]Javascript array push is not working

I am stuck on why this array push will not work... any help appreciated. 我被困在为什么这个数组推送不起作用的原因。任何帮助表示赞赏。

    var addons = new Array();

    myService.addon_dependencies(arr[i]['addoncode']).then(function(dependency) {
        console.log(dependency[0].addon_depend);  //returns A6002
        addons.push(dependency[0].addon_depend);
    });

    console.log(addons); //returns []   

This is because the addon_dependencies method is not finishing before you run console.log . 这是因为在运行console.log之前,addon_dependencies方法尚未完成。 The then method shows you're probably using some sort of promise framework. then方法显示您可能正在使用某种promise框架。 If you print it out in the then block it should work. 如果在then块中将其打印出来,它应该可以工作。

Array.push is working; Array.push正在运行; your code must be executed asynchronously, hence the empty addons . 您的代码必须异步执行,因此为空addons

console.log(addons) is executed before the item is beeing pushed into the array. 在将项目推入数组之前执行console.log(addons)。 So you see the empty array. 这样就看到了空数组。 Try the console.log after you push new items into it. 将新项目推送到console.log后,请尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM