简体   繁体   English

Javascript-返回函数中的数组长度

[英]Javascript - return array length in a function

I'm trying to get an array's length and display it on a page, like so: 我正在尝试获取数组的长度并将其显示在页面上,如下所示:

var someArray = ['item 1', 'item 2', 'item 3'];

var getArrayLength = function() {
    return someArray.length;
}

getArrayLength();

For some reason this isn't working. 由于某种原因,这不起作用。 I tried to replace the element's innerHTML, same issue. 我试图替换元素的innerHTML,同样的问题。

<p id="demo"></p>
document.getElementById("demo").innerHTML = someArray.length;

Even if I set a variable equal to someArray.length and then return the variable it doesn't work. 即使我设置了一个等于someArray.length的变量,然后返回该变量也不起作用。 I don't get any errors, just no result. 我没有任何错误,只是没有结果。 Is there something special about returning the length of an array in a function? 返回函数中数组的长度是否有特殊之处?

I was able to pull this off using jQuery, I'm just curious as to what I was doing wrong with the vanilla javascript. 我能够使用jQuery做到这一点,我只是好奇我在使用普通javascript做错了什么。

You don't even have to declare any functions. 您甚至不必声明任何函数。

 var someArray = ['item 1', 'item 2', 'item 3']; document.getElementById("demo").innerHTML = someArray.length; 
 <p id="demo"></p> 

actually your code is working but you are not actually trying to display anything. 实际上,您的代码正在运行,但实际上并没有尝试显示任何内容。 in your case add something actually giving you output. 在您的情况下,添加一些实际上可以给您输出的东西。

var someArray = ['item 1', 'item 2', 'item 3'];

var getArrayLength = function() {
    return someArray.length;
}

console.log(getArrayLength());
alert(getArrayLength());

You have to set the innerHTML (or textContent which is better) after the document is loaded. 加载文档后,您必须设置innerHTML (或更好的textContent )。 Try this: 尝试这个:

window.addEventListener("load", function() {
    document.getElementById("demo").textContent = someArray.length;
});

jQuery code was working because it's internally waiting for the load event (assuming that you've wrapped your code inside $(function() {...}) ). jQuery代码之所以起作用,是因为它在内部等待load事件(假设您已将代码包装在$(function() {...}) )。

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

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