按索引上下移动数组对象/元素

Ste*_*007 5 javascript arrays jquery object

我有一个带有向上和向下按钮的值列表。如果我想单击向上按钮,则元素会以列表中的先前值向上移动,然后单击向下按钮,它们会向下移动到列表中的下一项。我的示例代码在这里,

<ul>
  <li> 1 &nbsp;&nbsp;<button class="up">UP</button>&nbsp;&nbsp;<button class="down">DOWN</button></li>
  <li> 2 &nbsp;&nbsp;<button class="up">UP</button>&nbsp;&nbsp;<button class="down">DOWN</button></li>
  <li> 3 &nbsp;&nbsp;<button class="up">UP</button>&nbsp;&nbsp;<button class="down">DOWN</button></li>
  <li> 4 &nbsp;&nbsp;<button class="up">UP</button>&nbsp;&nbsp;<button class="down">DOWN</button></li>
  <li> 5 &nbsp;&nbsp;<button class="up">UP</button>&nbsp;&nbsp;<button class="down">DOWN</button></li>
</ul>

<script type="text/javascript">
function moveUp(element) {
  if(element.previousElementSibling)
    element.parentNode.insertBefore(element, element.previousElementSibling);
}
function moveDown(element) {
  if(element.nextElementSibling)
    element.parentNode.insertBefore(element.nextElementSibling, element);
}
document.querySelector('ul').addEventListener('click', function(e) {
  if(e.target.className === 'down') moveDown(e.target.parentNode);
  else if(e.target.className === 'up') moveUp(e.target.parentNode);
});
    </script>
Run Code Online (Sandbox Code Playgroud)

这是带有要显示的值列表的代码,但我希望以这种格式显示数组值,该格式根据索引执行向上和向下功能。我的数组元素是:

[
    { id: "Racer-101", rank: "1"},
    { id: "Racer-102", rank: "2"},
    { id: "Racer-103", rank: "3"},
    { id: "Racer-104", rank: "4"},
    { id: "Racer-105", rank: "5"},
    { id: "Racer-106", rank: "6"},
    { id: "Racer-107", rank: "7"},
    { id: "Racer-108", rank: "8"},
    { id: "Racer-109", rank: "9"}
]
Run Code Online (Sandbox Code Playgroud)

数组值怎么可能..

cнŝ*_*ŝdk 8

如果您想对您的 执行相同的操作array,您所需要做的就是检查给定的是否element有 aprevious或 anext元素,以便您可以交换两个对象以避免an index out of bound

您的代码应该是这样的:

function moveUp(id) {
  let index = arr.findIndex(e => e.id == id);
  if (index > 0) {
    let el = arr[index];
    arr[index] = arr[index - 1];
    arr[index - 1] = el;
  }
}
Run Code Online (Sandbox Code Playgroud)

要在 中向上移动elementarray,您需要确保这element 不是中的第一个元素array,然后执行交换操作。

function moveDown(id) {
  let index = arr.findIndex(e => e.id == id);
  if (index !== -1 && index < arr.length - 1) {
    let el = arr[index];
    arr[index] = arr[index + 1];
    arr[index + 1] = el;
  }
}
Run Code Online (Sandbox Code Playgroud)

向下移动element,您需要确保这element不是中的最后一个array

演示:

这是一个工作演示示例:

function moveUp(id) {
  let index = arr.findIndex(e => e.id == id);
  if (index > 0) {
    let el = arr[index];
    arr[index] = arr[index - 1];
    arr[index - 1] = el;
  }
}
Run Code Online (Sandbox Code Playgroud)