Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

Create a single value array in 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>
question from:https://stackoverflow.com/questions/7833806/create-a-single-value-array-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]);

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]

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...