简体   繁体   English

Javascript-函数外部的数组长度

[英]Javascript - array length outside of a function

I would like to know how can I use array.length outside of a function so I can work with that value elsewhere. 我想知道如何在函数外部使用array.length ,以便可以在其他地方使用该值。 I have this script: 我有这个脚本:

var length = url_ytb.length; //returns 2

function onPlayerStateChange(event) {      
    if(event.data === 0) { 
        array_position++;
        player.loadVideoById(url_ytb[array_position]);
        length--;
    }
}

if (length == 0) {
  alert("Good");
}

My problem is that the alert won't happen. 我的问题是警报不会发生。 I have printed the length variable but it still returns 2 when it should return 0. 我已经打印了length变量,但是当它应该返回0时它仍然返回2。

No. You can't as you are checking before the event itself. 不可以。您不能像在事件本身之前检查的那样。 You have to check it when the event occurs. 事件发生时,您必须检查它。 So it should be 所以应该

function onPlayerStateChange(event) {      
    if(event.data === 0) { 
        array_position++;
        player.loadVideoById(url_ytb[array_position]);
        length--;
    }
   if (length == 0) {
     alert("Good");
   }
}

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

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