增加数组中元素的值

时间:2019-04-01 03:34:10

标签: javascript arrays

说我有一个像这样的数组...

let myArr = [0,0,2,0,0];

我想创建一种波纹效果,使数组的结果为[0,1,2,1,0]

1 个答案:

答案 0 :(得分:2)

这将为您带来预期的结果:

let myArr = [0, 0, 2, 0, 0];


createRippleArray = (myArr) => {
  if (myArr.length % 2 === 0) {
    console.error("createRippleArray: Array length needs to be odd number>1");
    return [];
  }

  let midIndex = ~~(myArr.length / 2);
  let mid = myArr[midIndex];
  return myArr.map((e, i) => {
    let res;
    if (i < midIndex) {
      return ~~(mid / Math.abs(midIndex - i + 1));
    } else if (i === midIndex) {
      return mid;
    } else if (i > midIndex) {
      return ~~(mid / Math.abs(midIndex - i - 1));
    }
  });
}

console.log(createRippleArray(myArr));

希望这会有所帮助!