这是html代码
<body>
<section>
<h1>client profile informations</h1>
<div class="madaro" v-on:click.right.prevent>
<div>
<input v-model="newstu" type="text">
<input v-model="newgpa" type="number" @keyup.enter="addio">
<button @click="addio" > submit</button>
</div>
<h1 v-for="grade in grades">
Student {{grade.name}} has final grade {{grade.gpa}}
</h1>
</div>
</section>无论条件如何,每次都会推送新名称。
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
**the array**
grades:[
{
name:'pac',
gpa:'4'
},
{
name:'ray',
gpa:1.2
},
{
name:'ssy',
gpa:4.4
},
{
name:'snri',
gpa:3.5
},
{
name:'safa',
gpa:1.7
},
{
name:'mohammed',
gpa:5
},
{
name:'mammt',
gpa:4.1
}
],
newgpa:'',
newstu:''
},
*the function*
methods:{
addio(){
if (this.grades.name === this.newstu) {
console.log('hyhy');
} else {
return this.grades.push({name:this.newstu , gpa:this.newgpa});
}
**empty the input field**
this.newstu =''
this.newgpa=''
}
}
</script>
</body>发布于 2022-02-19 20:16:33
addio()实际上并没有检查条目是否已经存在于this.grades[]中。它只将newstu (新输入的学生名称)与this.grades.name进行比较,而this.grades.name并不存在,因为this.grades是Array。
一种解决方案是使用Array.prototype.find()搜索this.grades[]以寻找匹配的条目。每个对find()的回调都会收到一个数组条目,它可以用来比较条目的name属性和this.newstu。如果找不到条目,find()将返回undefined,因此您可以在if-statement中使用该调用:
if (this.grades.find(grade => grade.name === this.newstu)) {
// already exists...ignore
} else {
// new entry
this.grades.push({ name: this.newstu, gpa: this.newgpa })
}https://stackoverflow.com/questions/71188518
复制相似问题