我正在使用一个成绩计算器制作一个Webapp,可以在其中添加成绩并删除它们。它们保存在本地存储中。尝试删除指定等级时,它将删除最近添加的等级。如何专门删除数组中的int?
<template>
<div>
<h2>Grade-Calculator</h2>
<div>
<ul>
<li v-for="(g,idx) in grades" :key="idx">
{{idx+1}}. Grade : {{g}}
<button v-on:click="delGrade()">Delete</button>
</li>
</ul>
<div>
<label>New Grade:</label>
<input type="text" v-model="newGrade" />
<button v-on:click="addGrade()">Add</button>
</div>
<br />
<div>
<p>Average: {{ calcAvg() | round}}</p>
</div>
</div>
</div>
</template>
<!-- The Script-->
<script>
export default {
data: () => ({
grades: [],
newGrade: null,
avg: 0,
formattedNumber: ""
}),
name: "Home",
props: {},
methods: {
delGrade: function() {
var idx = this.grades.indexOf(this.grades);
this.grades.splice(idx);
localStorage.removeItem("grades");
localStorage.setItem("grades", this.grades);
}
},
mounted() {
this.grades = JSON.parse(localStorage.getItem("grades")) || [];
},
};
</script>
答案 0 :(得分:1)
首先,您需要在delGrade(gradeToDelete)
中删除等级,一旦获得该等级(及其索引为this.grades.indexOf(gradeToDelete)
),就可以使用该索引。
此外,我认为.splice需要deleteCount才能删除索引处的元素。尝试将this.grades.splice(idx);
更改为this.grades.splice(idx, 1);
答案 1 :(得分:1)
我假设您的数据看起来像数组中的整数。像下面的示例一样将它们存储在其中。
let grades = [8, 9, 5, 6, 3];
localStorage.setItem('grades', JSON.stringify(grades));
要从数组中删除单个键,请先将其解析回数组格式,然后使用Array.prototype.filter
方法创建一个没有要删除等级的新数组。
let gradeToRemove = 5;
let storedGrades = JSON.parse(localStorage.getItem('grades'));
let newGrades = storedGrades.filter(grade => grade !== gradeToRemove);
localStorage.setItem('grades', JSON.stringify(newGrades));
答案 2 :(得分:1)
您应提供要从数组中删除的ID
<button v-on:click="delGrade(idx)">Delete</button>
然后您应该收到该ID并使用它
delGrade: function(idToDelete) {
this.grades.splice(idToDelete, 1);
localStorage.removeItem("grades"); // it is not necessary, coz you will override all key grades in next line
localStorage.setItem("grades", this.grades);
}