Array.push()和唯一项 [英] Array.push() and unique items

查看:81
本文介绍了Array.push()和唯一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将唯一值推送到数组的简单情况。它看起来像这样:

I have a simple case of pushing unique values into array. It looks like this:

  this.items = [];

  add(item) {
    if(this.items.indexOf(item) > -1) {
      this.items.push(item);
      console.log(this.items);
    }
  }

看起来很直接,对吧?不,看起来如此。它不会添加任何值。我确信这是我身上某种愚蠢的错误,但我似乎无法找到它。

Seems pretty straight-forward, right? No, as it appears. It doesn't add any values. I am sure it's some kind of silly mistake on my side, but I can't seem to find it.

推荐答案

是的小错误

if(this.items.indexOf(item) === -1) {
      this.items.push(item);
      console.log(this.items);
    }

这篇关于Array.push()和唯一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆