[英]How do I program a button to display the length of an array? (in javascript)
<button onclick="lengthArray()">Item Quantity</button>
<p id="quant"></p>
var products = ["Printer", "Tablet", "Router", "Graphics Card","Cooling Fan"];
function lengthArray() {
products.length();
document.getElementById("quant").innerHTML = products.length();
}
Hello! 你好! I need some programming a button in javascript that can display the length of the array when the button has been clicked.
我需要对javascript中的按钮进行编程,当单击按钮时可以显示数组的长度。 The code above is my failed attempted to tackle this task, as nothing happens when the said button is clicked.
上面的代码是我为解决此任务而失败的尝试,因为单击该按钮时没有任何反应。 Edit: Thank you guys for helping me out !
编辑:谢谢你们帮助我!
Use products.length
instead of products.length()
for getting length of array 使用
products.length
而不是products.length()
获取数组的长度
var products = ["Printer", "Tablet", "Router", "Graphics Card","Cooling Fan"]; function lengthArray() { document.getElementById("quant").innerHTML = products.length; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button onclick="lengthArray()">Item Quantity</button> <p id="quant"></p>
change your code to: 将您的代码更改为:
function lengthArray() {
document.getElementById("quant").innerHTML = products.length; <<-- Remove "()"
}
Because length isn't a function. 因为长度不是函数。 it's a property :)
这是一个财产:)
<button onclick="lengthArray()">Item Quantity</button>
<p id="quant"></p>
var products = ["Printer", "Tablet", "Router", "Graphics Card","Cooling Fan"];
function lengthArray() {
document.getElementById("quant").innerHTML = products.length;
}
Just remove the brackets after length - to get the length of an array you have to use length
not length()
只需在长度后删除括号-要获取数组的长度,您必须使用
length
而不是length()
this is how your code should look like 这就是你的代码应该是什么样子
document.getElementById("quant").innerHTML = products.length;
and add a button to run the function 并添加一个按钮以运行该功能
<button onclick="lengthArray()">Button</button>
or you could just use your paragraph by adding a text to click on 或者您也可以通过添加文字来使用段落来单击
<p id="quant" onclick="lengthArray()">now visible</p>
hope it helps ! 希望能帮助到你 ! ^^
^^
try this: 尝试这个:
var products = ["Printer", "Tablet", "Router", "Graphics Card", "Cooling Fan"]; function lengthArray() { console.log(products.length); }
<button onclick="lengthArray()">Item Quantity</button> <p id="quant"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.