首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我想检查一下对象中的推送名称,如果它在数组中找到,它不会被重新推送,但无论如何都会被推送。

我想检查一下对象中的推送名称,如果它在数组中找到,它不会被重新推送,但无论如何都会被推送。
EN

Stack Overflow用户
提问于 2022-02-19 19:36:34
回答 1查看 29关注 0票数 0

这是html代码

代码语言:javascript
复制
<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>

无论条件如何,每次都会推送新名称。

代码语言:javascript
复制
    <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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-19 20:16:33

addio()实际上并没有检查条目是否已经存在于this.grades[]中。它只将newstu (新输入的学生名称)与this.grades.name进行比较,而this.grades.name并不存在,因为this.gradesArray

一种解决方案是使用Array.prototype.find()搜索this.grades[]以寻找匹配的条目。每个对find()的回调都会收到一个数组条目,它可以用来比较条目的name属性和this.newstu。如果找不到条目,find()将返回undefined,因此您可以在if-statement中使用该调用:

代码语言:javascript
复制
if (this.grades.find(grade => grade.name === this.newstu)) {
  // already exists...ignore

} else {
  // new entry
  this.grades.push({ name: this.newstu, gpa: this.newgpa })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71188518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档