javascript 存储在变量中时数组长度未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31221076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:29:08  来源:igfitidea点击:

Array length is undefined when stored in variable

javascriptarrays

提问by Peter Piper

In the following w3schools example- why does this return 3

在以下w3schools 示例中- 为什么返回 3

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var cars = [
    "Saab",
    "Volvo",
    "BMW"
];
document.getElementById("demo").innerHTML = cars.length; //returns 3

</script>

</body>
</html>

and when I try to store cars.length in a variable it returns undefined?

当我尝试将 cars.length 存储在变量中时,它返回未定义?

var test = cars.lenght;
document.getElementById("demo").innerHTML = test; // returns undefined

回答by Branko Sego

You have spelling mistake

你有拼写错误

 var test = cars.length;

回答by Mark Eriksson

cars.lenght

???

???

"lenght" != "length"

“长度”!=“长度”

回答by Lucky

Typo mistake. You have undefined property (lenght) to access the length property of your array. You should instead use

打字错误。您有未定义的属性 ( lenght) 来访问数组的长度属性。你应该改用

cars.length

cars.length

which gives you the length of the array cars - 3. So var test will have 3 assigned to it.

这为您提供了数组汽车的长度 - 3。因此 var test 将分配给它 3。

回答by Malik Naik

Obviously, cars.lengthreturns 3because we are trying to get the length of array.

显然,cars.length返回3是因为我们试图获取数组的长度。

function myFunction() {
var index;
var text = "<ul>";
var cars= [
  "Saab",
  "Volvo",
  "BMW"];
for (index = 0; index < cars.length; index++) {
    text += "<li>" + cars[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}

check forloop in the above example it uses index < cars.length

for在上面的例子中检查循环它使用index < cars.length

Output of above code will be

上面代码的输出将是

  • Saab
  • Volvo
  • BMW
  • 萨博
  • 沃尔沃
  • 宝马