如果两个值都不存在,我如何推入数组?这是我的数组:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()

我该怎么做呢?


当前回答

我想我在这里回答太迟了,然而这是我最终想出的一个邮件管理器我写。好的,这就是我需要的。

窗口。ListManager = []; $(' #添加').click(函数(){ / /你的功能 let data =Math.floor(Math.random() * 5) + 1 如果(window.ListManager.includes(数据)){ Console.log("数据存在于列表") 其他}{ window.ListManager.push(数据); } $(' #结果')。text (window.ListManager); }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <标题>独特列表< / h1 > < p id = "结果" > < / p > </button> . <button id="add">添加到列表中

其他回答

如果你需要一些简单的东西,而不想扩展数组原型:

// Example array
var array = [{id: 1}, {id: 2}, {id: 3}];

function pushIfNew(obj) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === obj.id) { // modify whatever property you need
      return;
    }
  }
  array.push(obj);
}

A是你拥有的对象数组

a.findIndex(x => x.property=="WhateverPropertyYouWantToMatch") <0 ? 
a.push(objectYouWantToPush) : console.log("response if object exists");

你可以用一个自定义方法扩展Array原型:

// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) { 
    for(var i=0; i < this.length; i++) { 
        if(comparer(this[i])) return true; 
    }
    return false; 
}; 

// adds an element to the array if it does not already exist using a comparer 
// function
Array.prototype.pushIfNotExist = function(element, comparer) { 
    if (!this.inArray(comparer)) {
        this.push(element);
    }
}; 

var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) { 
    return e.name === element.name && e.text === element.text; 
});

如果不在列表中,则添加

对于一个简单值的列表,它是一行程序…

[...new Set([...someArray, someElement])]

JavaScript的用法:

var myArray = ['bill','bob']
var alreadyIn = [...new Set([...myArray, 'bob'])] // ['bill','bob']
var notAlreadyIn = [...new Set([...myArray, 'peter'])] // ['bill','bob','peter']

TypeScript文本(注意include vs includes):

interface Array<T> {
  include(element: T): Array<T>
}
Array.prototype.include = function (element: any): any[] {
  return [...new Set([...this, obj])]
}

...但对于对象来说,情况就复杂多了

[...new Set([...someArray.map((o) => JSON.stringify(o)),
    JSON.stringify(someElement)]).map((o) => JSON.parse(o))

TypeScript文本处理任何事情:

Array.prototype.include = function (element: any): any[] {
  if (element && typeof element === 'object')
    return [
      ...new Set([
        ...this.map((o) => JSON.stringify(o)),
        JSON.stringify(element),
      ]),
    ].map((o) => JSON.parse(o))
  else return [...new Set([...this, element])]
}

如果你的项目包含lodash,使用unionBy方法会很简单

import {unionBy} from "lodash";

let arrayObj = [
    { name: "jhon", text: "guitar"},
    { name: "paul", text: "bass" },
    { name: "george", text: "guitar" }
];

// this object will be added to the array
arrayObj = unionBy(arrayObj, [{name: 'ringo', text: 'drums'}], 'name')

// this object will be ignored because already exists  
arrayObj = unionBy(arrayObj, [{name: "jhon", text: "guitar"}], 'name')