如果新对象未定义则推送它,并在可用时忽略

时间:2017-06-22 06:42:18

标签: javascript arrays json push

我想将新对象推送到JSON数组(如果它尚不可用)并忽略它(如果可用)。例如,如何在第二次单击按钮时忽略此代码中的登录:

var things = [];

$("#button").click(function(){
things[0]["id456"] != undefined ? console.log("ignored") : things.push({"id456":"clicked"});
$("#output").text(JSON.stringify(things));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>
<button id="button">
Click
</button>

我知道我可以这样做:

var strThings = JSON.stringify(things);
var available = strThings.search("id456");
available === -1 ? things.push({"id456":"clicked"}) : console.log("ignored");

但我不认为这是个好主意。

1 个答案:

答案 0 :(得分:3)

使用Array#some()

&#13;
&#13;
var things = [];

$("#button").click(function() {
  things.some(thing => thing.id456 !== undefined) ? console.log("ignored") : things.push({
    "id456": "clicked"
  });
  $("#output").text(JSON.stringify(things));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>
<button id="button">Click</button>
&#13;
&#13;
&#13;

但如果您需要我的建议,请不要尝试在一条线上执行此操作。这些令人惊奇的事情被称为if and else statements

&#13;
&#13;
var things = [];

$("#button").click(function() {
  let containsId456 = things.some(
    thing => thing.id456 !== undefined
  );

  if (containsId456) {
    console.log("ignored");
  } else {
    things.push({"id456": "clicked"});
  }
  $("#output").text(JSON.stringify(things));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>
<button id="button">Click</button>
&#13;
&#13;
&#13;

但最后,除非我遗漏了某些内容,否则使用Map或用作ID字典的对象会更容易:

&#13;
&#13;
var things = new Map();

$("#button").click(function() {
  if (things.has("id456")) {
    console.log("ignored");
  } else {
    things.set("id456", "clicked");
  }
  $("#output").text(JSON.stringify([...things]));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>
<button id="button">Click</button>
&#13;
&#13;
&#13;