Reputation: 17
I'd like to know how to create an array like the following with a for loop (notice that the accepted answer includes 0 while it was not part of my requirements. I guess I should meditate on this and stop ignoring people's comments).
var arr = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
My try can't print the negative numbers in array.
for (var i = -10; i <= 10; i++) {
arr[i] = i;
}
Result:
0,1,2,3,4,5,6,7,8,9,10
I also don't want the negative numbers of indexes in the array.
arr[-10]....arr[-9].....arr[1]...
Upvotes: 1
Views: 3286
Reputation: 4414
In order to provide the desired sequence of -10 to -1 then 1 to 10 without the 0, consider the following:
var arr = [];
for(var i = -10; i < 0; i++) arr[i + 10] = i;
for(var i = 1; i <= 10; i++) arr[i + 10] = i;
If you want to use the same loop with a different range, just define a variable to replace 10 every time you see it in the code given above.
Upvotes: 1
Reputation: 191946
If you push to the array, you don't have to state the index:
var i, arr = [];
for (i = -10; i <= 10; i++) {
arr.push(i);
}
If you need to skip 0:
for (i = -10; i <= 10; i++) {
i !== 0 && arr.push(i);
}
Upvotes: 7
Reputation: 1355
Use this :
var array = new Array();
var arrayIndex = 0;
for(var i=-10; i<=10;i++){
array[arrayIndex++] = i;
}
Array indexes start at 0 and cannot be negative.
Explanation:
The first line declares the array.
The second line declares a variable named arrayIndex
.
The for
loop iterates through all the numbers ranging between -10 to 10 and assigning all those values from array[0]
to array[20]
Upvotes: 0
Reputation: 36609
As I don't see
0
in question:
var arr = [];
for (var j = 1; j <= 10; j++) {
arr.push(j);
arr.unshift((j) * (-1));
}
document.getElementById('data').innerHTML = JSON.stringify(arr);
<div id="data"></div>
Upvotes: 2
Reputation: 1208
var arr = [];
for (var j = -10; j <= 10; j++)
arr[arr.length] = j;
Upvotes: 2
Reputation: 2151
Try this way:
for (int i = 0; i <= 20; i++)
{
arr [i] = i - 10;
}
Indexes in an array always starts from 0 and can't be negative so if you need negative values at positive indexes some computations or translation of values must take place.
Upvotes: 6