[英]how to create negative numbers in array by loop?
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). 我想知道如何使用for循环创建类似以下的数组(请注意,接受的答案包括0,而这并不是我的要求的一部分。我想我应该对此进行沉思,并停止忽略人们的评论)。
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]...
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: 如果您需要跳过0:
for (i = -10; i <= 10; i++) {
i !== 0 && arr.push(i);
}
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. 数组中的索引始终从0开始并且不能为负,因此,如果在正索引处需要负值,则必须进行一些计算或值转换。
var arr = [];
for (var j = -10; j <= 10; j++)
arr[arr.length] = j;
As I don't see
0
in question: 我没有看到有问题的0
:
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>
In order to provide the desired sequence of -10 to -1 then 1 to 10 without the 0, consider the following: 为了提供所需的顺序,从-10到-1,然后从1到10,不带0,请考虑以下几点:
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. 如果要在不同的范围内使用相同的循环,只需定义一个变量,即可在每次在上面的代码中看到它时每次替换10。
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. 数组索引从0开始,不能为负。
Explanation: 说明:
The first line declares the array. 第一行声明数组。
The second line declares a variable named arrayIndex
. 第二行声明一个名为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]
for
循环遍历介于-10到10之间的所有数字,并将所有这些值从array[0]
分配给array[20]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.