[英]How to operate the elements of an array
I have to operate a 4 elements array, calculating the difference between the adjacent elements and creating a new array with the resulting differnece. 我必须操作一个4个元素的数组,计算相邻元素之间的差异,并使用产生的差异创建一个新的数组。 The last element should be colindant with the first one.
最后一个元素应与第一个元素保持一致。
example: 例:
firstArray=[0,1,2,3];
secondArray = newArray();
The second array will be: 第二个数组将是:
secondArray[0]: 1-0 = 1
secondArray[1]: 2-1 = 1
secondArray[2]: 3-2 = 1
secondArray[3]: 3-0 = 3
So the new Array should be secondArray=[1,1,1,3]
因此,新的Array应该为
secondArray=[1,1,1,3]
I tried to do it with a for loop but when the third array is going to be operate it always operate the firstArray[3] - secondArray[0]... when it should be fistArray[3] - firstArray[0] 我试图用一个for循环来做到这一点,但是当要操作第三个数组时,它总是要操作firstArray [3]-secondArray [0] ...当它应该是fistArray [3]-firstArray [0]时
How can operate the firstArray to differentiate it from the new created secondArray? 如何操作firstArray使其与新创建的secondArray区分?
Thank you! 谢谢!
You never said anythign about a 3rd array in your example. 在您的示例中,您从未对第3个数组说过任何话。
Is this what you're trying to do? 这是您要做什么?
secondArray[0] = firstArray[1]-firstArray[0];
secondArray[1] = firstArray[2]-firstArray[1];
secondArray[2] = firstArray[3]-firstArray[2];
secondArray[3] = firstArray[0]-firstArray[3];
If you are in a loop, the expression could be 如果您处于循环中,则表达式可能是
secondArray[i] = firstArray[(i+1)%arrayLength]-firstArray[i];
UPDATE: 更新:
secondArray[i] = Max(firstArray[(i+1)%arrayLength],firstArray[i]) - Min(firstArray[(i+1)%arrayLength],firstArray[i]);
Using Max and Min will get the larger and smaller of the two elements in question. 使用最大和最小将得到所讨论的两个元素中的更大和更小。 Does that help?
有帮助吗?
in your loop: 在您的循环中:
if (i == 3)
firstArray[i] - firstArray[0];
Try this: 尝试这个:
var firstArray = [0,1,2,3],
secondArray = [];
firstArray.forEach(function(val, i, arr) {
secondArray[i] = arr[(i+1)%arr.length] - val;
});
Edit A solution without forEach
: 编辑没有
forEach
的解决方案:
for (var i=0; i<firstArray.length; ++i) {
secondArray[i] = firstArray[(i+1)%firstArray.length] - firstArray[i];
}
input = [1, 4, 19, -55, 20];
function f(a) {
function next(a) {
var t = [], l = a.length;
for (var i = 1; i < l; ++ i)
t.push(Math.abs(a[i] - a[i-1]));
t.push(Math.abs(a[l-1] - a[0]));
return t;
}
var l = a.length;
var result = [a];
for (var i = 0; i < l-1; ++ i)
result.push(next(result[i]));
return result;
}
f(input);
// [[1, 4, 19, -55, 20], [3, 15, 74, 75, 19], [12, 59, 1, 56, 16], [47, 58, 55, 40, 4], [11, 3, 15, 36, 43]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.