简体   繁体   English

javascript中函数之外的获取数组值的问题?

[英]issue with get array values outside the function in javascript?

I have created an array which will store dynamic values coming from DB. 我创建了一个数组,该数组将存储来自DB的动态值。 When I print the array inside the transaction function it is printing. 当我在事务功能中打印数组时,它正在打印。 when I tried to print out side I didn't get the values. 当我尝试打印出一面时,我没有得到值。 I have declared the array globally. 我已经全局声明了数组。 what is the problem, my code is as follows; 有什么问题,我的代码如下:

function sendCategoryDetails() {

    var selected_category = $('#select-choice :selected').val();
    alert("control : " + selected_category);
    var mycoodinatesDetails;
    var myLocation = new Array();
    var db = window.sqlitePlugin.openDatabase({name: "MYDB"});

    db.transaction(function (tx) {
        tx.executeSql("select Location from Locationlog WHERE Category = '"+selected_category+"';", [], 
            function (tx, res) {
                for (var i = 0; i < res.rows.length; i++) {
                    myLocation[i] = res.rows.item(i).Location;
                }
                alert (myLocation +" length : "+ myLocation.length); // Values are printing 
            });
    });
    alert (myLocation +" length : "+ myLocation.length); // values are not getting, It showing the length is 0
}

Any suggestions? 有什么建议么?

tx.executeSql is an async function. tx.executeSql是一个异步函数。 The alert works within the function since that is the callback and the async processing has finished. alert在函数内起作用,因为这是回调 ,并且异步处理已完成。 The alert after the function is trigger before the function has finished, thus being undefined . 功能完成之前触发功能后的alert ,因此undefined

Solution: Do the work inside the callback or call another function with the array passed as a parameter and do the work there. 解决方案:在回调内部进行工作,或使用作为参数传递的数组调用另一个函数,然后在此处进行工作。

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

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