javascript – 将数组拆分为从负到正的范围

前端之家收集整理的这篇文章主要介绍了javascript – 将数组拆分为从负到正的范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我有一个数组级别包含其他名为level的数组,这些数组包含阶段.

我想用一个名为position的新属性映射一个级别内的所有对象.该位置返回距阵列中心的距离.按中心我的意思是长度/ 2.

如果数组长度是偶数,我想要以下范围

… -3.5,-2.5,-1.5,-0.5,0.5,1.5,2.5,3.5 …

如果数组长度不均匀,我想要以下范围

… -4,-3,-2,-1,1,2,3,4 …

我开始创造这个

const distanceLevels = [
  [{
    "id": 1
  },{
    "id": 8
  }],[{
    "id": 2
  }],[{
    "id": 3
  },{
    "id": 4
  },{
    "id": 5
  },{
    "id": 7
  }],[{
    "id": 6
  }]
];

function getViewLevels() {
  const viewLevels = []; // the new array as the result

  distanceLevels.forEach(level => { // one level containing the stages
    const levelLength = level.length;
    const halfLevelLength = levelLength * 0.5;
    const levelLengthIsEven = levelLength % 2 == 0;

    let viewLevel = []; // the mapped level

    if (levelLengthIsEven) {
      addViewStage(viewLevel,level[Math.floor(halfLevelLength)],0);
    }

    for (let i = 0; i < halfLevelLength; i++) {
      let rightPosition = i - halfLevelLength;
      let leftPosition = i;
      let leftStageIndex = i;

      if (levelLengthIsEven) {
        leftPosition++;
        leftStageIndex += Math.floor(halfLevelLength) + 1;
      } else {
        rightPosition += 0.5;
        leftPosition += 0.5;
        leftStageIndex += halfLevelLength;
      }

      addViewStage(viewLevel,level[i],rightPosition);
      addViewStage(viewLevel,level[leftStageIndex],leftPosition);
    }

    viewLevel = viewLevel.sort((a,b) => a.position > b.position); // sort the result by their position,means from negative to positive
    viewLevels.push(viewLevel); // add this new view level
  });

  console.log(viewLevels); // <---- result here!
}

function addViewStage(viewLevel,stage,position) { // push a new element to the array
  viewLevel.push({
    stage: stage,position: position
  });
}

getViewLevels();

这是我得到的结果

我真的很挣数学.我想做的就是从中映射每个对象

阶段(对象)

{
   stage: stage,position: position // with the correct range
}

解决方法

你可以用两个嵌套的地图做到这一点:
const distanceLevels = [
  [{
    "id": 1
  },[{
    "id": 6
  }]
]

const mappedLevels = distanceLevels.map(level =>
  level.map((stage,index,lvl) => (
    {...stage,position: index - (lvl.length - 1) / 2}
  ))
);

console.log(mappedLevels);
原文链接:https://www.f2er.com/js/158478.html

猜你在找的JavaScript相关文章