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?
-
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
3 Answers
Reset to default 4Try 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
版权声明:本文标题:javascript - How to replace the last element of an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743967528a2570163.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论