检查对象/数组中的唯一值

时间:2016-11-07 22:08:48

标签: javascript arrays object

我再次。我终于用我编写的脚本完成了最后一部分,现在我唯一需要尝试做的就是检查唯一值。

下面是我编写的脚本,但它不起作用。任何帮助,将不胜感激。因为我添加了'for'循环,它似乎根本没有响应。我正在尝试检查数组中的重复项。

var garrCust = []; // an array of id -> {id:"", name:"", amount:""}

function addCust(){
    var custID = document.getElementById("custid").value;
    var custName = document.getElementById("custname").value;
    var custAmount = document.getElementById("amount").value;
    var i;

    if(!custID){
        document.getElementById("output").innerHTML = "ID Cannot be Blank";
        return false;}

    for(i = 0; i < garrCust.length; i++){
        if(garrCust[i].hasOwnProperty(custID)){
            document.getElementById("output").innerHTML = "ID already Exists!";
            return false;}
        else{
            garrCust.push({id: custID, name: custName, amount: custAmount});
            document.getElementById("output").innerHTML = "Added ID " + custID;
            return true;}
    }
}

1 个答案:

答案 0 :(得分:1)

循环应遍历整个数组以检查ID是否存在。

第一次添加客户时,它不会进入循环,因为数组是空的

请在下面找到一个工作代码段

&#13;
&#13;
var garrCust = []; // an array of id -> {id:"", name:"", amount:""}

function addCust() {
  var custID = document.getElementById("custid").value;
  var custName = document.getElementById("custname").value;
  var custAmount = document.getElementById("amount").value;
  var output = document.getElementById("output");
  var list = document.getElementById("list");
  
  //Input ID is empty
  if (!custID) {
    document.getElementById("output").innerHTML = "ID Cannot be Blank";
    return false;
  }
  
  //Create the customer object
  var myCustomer = {
    "id": custID,
    "name": custName,
    "amount": custAmount
  };

  //Check if ID already exists
  for(let i=0; i<garrCust.length;i++){
    if(garrCust[i].id === custID){
      output.innerHTML = "ID already exists !";
      output.style.color = "red";
      return false;
    }
  }
  
  //ID was not found thus add the new customer
  garrCust.push(myCustomer);
  output.innerHTML = "Customer added";
  output.style.color = "green";
  list.innerHTML += custID + " - ";
}
&#13;
ID
<input type="text" id="custid">Name
<input type="text" id="custname">Amount
<input type="number" id="amount">

<input type="submit" onclick="addCust()" value="Add customer">

<br/>

<p id="output"></p>

<p id="list"></p>
&#13;
&#13;
&#13;