在 JavaScript 中创建单值数组 [英] Create a single value array in JavaScript
问题描述
为什么下面的代码显示undefined
?我们不允许创建具有单个值的数组吗?放置两个值不会显示此错误.这是 Javascript 的问题吗?
why is the following code showing undefined
? Are we not allowed to create an array with a single value? Putting two values won't show this error. Is this a problem with Javascript?
<script>
var tech = new Array(21);
alert(tech[0]);
</script>
推荐答案
new Array(21)
创建一个长度为 21 的数组.如果要创建一个单值数组,包含一个数字,使用方括号,[21]
:
new Array(21)
creates an array with a length of 21. If you want to create a single-value array, consisting of a number, use square brackets, [21]
:
var tech = [ 21 ];
alert(tech[0]);
如果你想动态填充一个数组,使用.push
方法:
If you want to dynamically fill an array, use the .push
method:
var filler = [];
for(var i=0; i<5; i++){
filler.push(i); //Example, pushing 5 integers in an array
}
//Filler is now equivalent to: [0, 1, 2, 3, 4]
当 Array 构造函数接收到一个参数 p
时,它是一个正数,就会创建一个由 p 元素组成的数组.此功能可用于重复字符串,例如:
When the Array constructor receives one parameter p
, which is a positive number, an array will be created, consisting of p elements. This feature is can be used to repeat strings, for example:
var repeat = new Array(10);
repeat = repeat.join("To repeat"); //Repeat the string 9x
这篇关于在 JavaScript 中创建单值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!