简体   繁体   English

Javascript数组从数组中的每个元素中减去一个值

[英]Javascript arrays subtract a value from every element in array

I have the following code written and I have no idea why it is not working.我编写了以下代码,但我不知道为什么它不起作用。 Essentially, I am trying to subtract 255 from every value in an array, but it must be ordered where 255 is first (I can't just do i - 255, it won't get me the values I need).本质上,我试图从数组中的每个值中减去 255,但它必须在 255 的第一个位置进行排序(我不能只做 i - 255,它不会得到我需要的值)。 I have also tried i+-255 to no avail.我也试过 i+-255 无济于事。

function makeReverse(original, output){
  for (i=0; i<original.length; i++) {
    output[i]=original[i]; //copy original array to output array
    if ((i % 4) !== 3) {
      output[i] = output[255 - i]; //why this is not working is beyond me the 
                                     values keep reading 0 for rgb
    }
  }
  console.log(output);
  return output;
}

Easiest way would be using map .最简单的方法是使用map Something like this:像这样的东西:

original.map(function(element){
   return element - 255;
});

Or in ES6:或者在 ES6 中:

original.map(element => element - 255);

Or if you only want to subtract from the value under a condition:或者,如果您只想从某个条件下的值中减去:

original.map(function(value){
   if(value % 4 !== 3){
       return value - 255;
   } else {
       return value;
   }
});

Check here to find out how map works.点击此处了解map工作原理。

why you subtracting from index [i-255] .为什么要从索引 [i-255] 中减去。 subtract it from value like this从这样的值中减去它

output[i] = output[i]-255; 

I think you are looking for我想你正在寻找

output[i] = original[255 - i];

This would make your output array the reverse-order of the original array (for elements whose index is not 3 mod 4).这将使您的输出数组与原始数组相反(对于索引不是 3 mod 4 的元素)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM