简体   繁体   English

使用Azure平台访问数组位置返回的JavaScript中未定义

[英]Accessing array position returns undefined in JavaScript using Azure platform

I have the following JavaScript object: 我有以下JavaScript对象:

var payload = {
    "data": {
        "title": item.title,
        "time": item.time,
        "location": item.location,
        "latitude": item.latitude,
        "longitude": item.longitude,
        "invites": item.invites,
        "encodedImage": item.encondedImage        
    }
};

item.invites is a big string separated by commas. item.invites是一个大字符串,用逗号分隔。 I use a function to split the string into an array based on the commas: 我使用一个函数根据逗号将字符串拆分为一个数组:

var userIdArray = splitArray(item.invites);
userIdArray.pop(); //last element is empty

//further down...
function splitArray(str) {
    var array = new Array(); //explicitly declared out of despair
    array = str.split(",");    
    return array;
}

and then I iterate it like so: 然后像这样迭代它:

for (var i = 0; i < userIdArray.length; i++) {
     request.execute({
         success: function() {
            console.log("User: " + userIdArray[i]); //prints undefined...

But even though console.log(userIdArray); 但是即使console.log(userIdArray); prints the array normally, I get undefined if the array is only 1 in length, but if it's 2 it prints the 2nd element... Why is this happening? 正常打印数组,如果数组只有1个长度,我不确定,但是如果数组只有2个,它将打印第二个元素...为什么会这样?

I'm not familiar with Azure, but going by the general pattern of the code, it seems that success is a function which will execute in the future and is not tied to the loop scope: therefore it will see a bad counter variable [i] value when the handler executes. 我对Azure不熟悉,但是按照代码的一般模式来看, success似乎是一个将在将来执行的函数,并且与循环作用域无关:因此它将看到错误的计数器变量[i]处理程序执行时的[i]值。

(Also, it may not pose a problem, but a counter variable declared and initialized in the loop header is a code smell, and possibly problematic.) (此外,它可能不会造成问题,但是在循环头中声明和初始化的计数器变量是代码异味,并且可能有问题。)

Without looking at the complete code, I can't tell if [i] is a global or local to a wrapping function, but I think it is global since you didn't get a ReferenceError. 如果不看完整的代码,就无法确定[i]是包装函数的全局变量还是局部变量,但是我认为它是全局变量,因为您没有得到ReferenceError。

The loop executes without waiting for all the future success calls (which are are async-stacked and not synchronous with the loop body), and so the last [i++] is evaluated at array.length, which will always be undefined since we're indexing past the array. 循环的执行无需等待将来的所有成功调用(这些调用都是异步堆栈的,并且与循环体不同步),因此最后一个[i++]的计算结果为array.length,由于我们通过数组索引。

request.execute is synchronous and will be dispatched as expected from within the loop body, but the success handler is surely not. request.execute是同步的,将从循环体内按预期方式分派,但成功处理程序肯定不是。

As for the expressing the intention correctly in code, I think that an IIFE might fix this: (I have zero idea what request.execute does and if calling execute on the same object time and again is ok, hence I say it might ): 而对于在代码中正确表达意愿,我认为一个IIFE可能解决这个问题:(我有零想法确实,如果调用execute同一对象时,再次是确定的,所以我说什么request.execute它可能 ):

for (var i = 0; i < userIdArray.length; i++) {
     request.execute({
        success: (function (counter) {
            return function () {
                console.log("User: " + userIdArray[counter]);
            }
        }(i))
    });
 }

I'm throwing a reasonable guess here. 我在这里提出一个合理的猜测。 That aside, I think the code needs significant re-thinking and refactoring. 除此之外,我认为代码需要大量的重新思考和重构。 Callbacks in loops usually indicate a major logical flaw. 循环中的回调通常表示一个主要的逻辑缺陷。

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

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