admin管理员组

文章数量:1355754

I need to replace last element in array.

I know, that I can use filter method to replace element, but how to replace the latest element?
How do I know the index of element?
Should I check size of array and replace latest element?
or maybe remove latest element and add new?

Generally i'm adding elements using unshift:

this.array.unshift({
    name: cmd.event.type,
    id: cmd.event.id,
    xpath: cmd.event.xpath,
    x: `x: ${xparam}`,
    y: `y: ${yparam}`,
})

and what should I do to replace latest this.array element?

I need to replace last element in array.

I know, that I can use filter method to replace element, but how to replace the latest element?
How do I know the index of element?
Should I check size of array and replace latest element?
or maybe remove latest element and add new?

Generally i'm adding elements using unshift:

this.array.unshift({
    name: cmd.event.type,
    id: cmd.event.id,
    xpath: cmd.event.xpath,
    x: `x: ${xparam}`,
    y: `y: ${yparam}`,
})

and what should I do to replace latest this.array element?

Share Improve this question edited Oct 13, 2021 at 12:24 KyleMit 30.7k72 gold badges510 silver badges702 bronze badges asked May 25, 2021 at 20:05 IlkarIlkar 2,18711 gold badges46 silver badges76 bronze badges 2
  • 4 this.array[this.array.length - 1] = /* Whatever you want */ – Guerric P Commented May 25, 2021 at 20:07
  • 1 @GuerricP in Vue 2 this is not reactive – Boussadjra Brahim Commented May 25, 2021 at 20:14
Add a ment  | 

3 Answers 3

Reset to default 4

Try to use splice method :

this.array.splice(this.array.length - 1, 1, {
        name: cmd.event.type,
        id: cmd.event.id,
        xpath: cmd.event.xpath,
        x: `x: ${xparam}`,
        y: `y: ${yparam}`,
      })

the 1st param : the element index to be replaced

2nd param: the delete count

3rd param : your new element to insert

for Vue 2 you could use this.$set method :

 this.$set(this.array,this.array.length - 1,{
    name: cmd.event.type,
    id: cmd.event.id,
    xpath: cmd.event.xpath,
    x: `x: ${xparam}`,
    y: `y: ${yparam}`,
  })

You could get latest element index with length property

 const latestElement = this.array[this.array.length - 1]

using index is IMHO more readable than splice when replacing the last item

this.array[this.array.length - 1] = {
    ...item props...
};

maybe pop&push is even nicer

this.array.pop()
this.array.push({
    ...item props...
});
enter code here

but you wrote that you are adding items using unshift, which adds to beginning of array, so if you ment "latest" as "latest added by unshift", then replacing is just

this.array[0] = {
    ...item props...
};

or just remove latest added

this.array.shift();

as it removes forst element in array

本文标签: javascriptHow to replace the last element of an arrayStack Overflow