【问题标题】:How I can rearrange the last element of an array to the first place? [duplicate]如何将数组的最后一个元素重新排列到第一位? [复制]
【发布时间】:2020-06-08 02:25:25
【问题描述】:

我在 javascript 中有一个对象数组:

shapeToolsTarget: Array(4)
0: {id: 20, name: "Background", type: "shape"}
1: {id: 21, name: "BorderColor", type: "shape"}
2: {id: 22, name: "BorderWeight", type: "shape"}
3: {id: 3, name: "Paste", type: "text"}

如何将数组的最后一个元素重新排列到第一位?像这样:

shapeToolsTarget: Array(4)
0: {id: 3, name: "Paste", type: "text"}
1: {id: 20, name: "Background", type: "shape"}
2: {id: 21, name: "BorderColor", type: "shape"}
3: {id: 22, name: "BorderWeight", type: "shape"}

【问题讨论】:

  • 您是否尝试过可以向我们展示的内容?然后我们可以提供帮助
  • @Calvin Nunes 我尝试了 array_shift() 函数,但没有带来结果..

标签: javascript


【解决方案1】:

您可以使用unshift()pop() 的组合。

unshift() 方法将一个或多个元素添加到数组的开头并返回数组的新长度。

pop() 方法从数组中删除 last 元素并返回该元素。这个方法改变了数组的长度。

var items = ['A', 'B', 'C'];
console.log(items);

items.unshift(items.pop());
console.log(items);

【讨论】:

  • 谢谢!但我有 4 个元素而不是 3 个,我得到 0: {id: 22, name: "BorderWeightComponent", type: "shape"} 1: {id: 3, name: "Paste", type: "text"} 2 : {id: 20, name: "Background", type: "shape"} 3: {id: 21, name: "Border", type: "shape"}
  • 数组中元素的数量和类型无关紧要,我添加了描述以阐明这两种方法的工作原理。只需shapeToolsTarget.unshift(shapeToolsTarget.pop());
  • 好的!但我把这个元素排在第二位!而不是第一个..
【解决方案2】:

您可以为此使用pop()unshift() 数组方法:

  • pop() 从数组中删除最后一个元素。
  • unshift(value)value 添加到数组的开头。

let shapeToolsTarget = [
{id: 20, name: "Background", type: "shape"},
{id: 21, name: "BorderColor", type: "shape"},
{id: 22, name: "BorderWeight", type: "shape"},
{id: 3, name: "Paste", type: "text"}];

shapeToolsTarget.unshift(shapeToolsTarget.pop())

console.log(shapeToolsTarget)

【讨论】:

  • 谢谢!但我使用你的代码 0: {id: 22, name: "BorderWeightComponent", type: "shape"} 1: {id: 3, name: "Paste", type: "text"} 2: {id : 20, name: "Background", type: "shape"} 3: {id: 21, name: "Border", type: "shape"} 它在第二位..
  • 代码已更新。请重试。
猜你喜欢
  • 2021-03-14
  • 2020-02-04
  • 2014-01-27
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2016-12-07
相关资源
最近更新 更多