可以使用splice()方法来在数组中切换值并保持在原来的位置。以下是一个示例:
在组件中定义一个数组并初始化:
items = ['A', 'B', 'C', 'D'];
编写一个函数,在该函数中使用splice()方法来切换值:
toggleItem(item: string) {
const index = this.items.indexOf(item);
if (index !== -1) {
const newItem = item === 'A' ? 'B' : 'A';
this.items.splice(index, 1, newItem);
}
}
在模板中循环遍历数组,并调用切换函数:
-
这个示例中,当用户点击列表中的按钮时,系统将切换在数组中的值。由于使用了splice()方法,切换后的值仍将保持在原来的位置。