【问题标题】:Checking for an item in an array检查数组中的项目
【发布时间】:2018-08-07 18:50:36
【问题描述】:

我无法找到正确的方法来查找 for 循环中的项目是否在数组中。假设我有一个 for 循环,它正在迭代一些结果。如果它们在一个数组中:

 ctids = [];

继续for 循环中的下一步,但如果没有,则将它们推送到数组并执行其他操作。正确的语法是什么?

for (var i=0;i<results.features.length;i++){
          ACS_BG = results.features[i].attributes.BLKGRPCE;
          ACS_ST = results.features[i].attributes.STATEFP;
          ACS_CNTY = results.features[i].attributes.COUNTYFP;
          ACS_TRCT = results.features[i].attributes.TRACTCE;

    if ACS_TRCT exists in ctids { //This is where I am having trouble. 
        continue;       //skip the rest of the if statement
    } else {
        ctids.push(ACS_TRCT);
    //   do something else;
    };
};

【问题讨论】:

  • ctids 不是一个数组,因为您将{} 分配给它,所以.push 将不起作用。你想达到什么目的?你能显示预期的输出吗?
  • 对不起;将其固定为数组。
  • 请添加一些数据和想要的结果。
  • 预期结果是,如果`ACS_TRCT`不在`ctids`数组中,则将该值推到那里。所以,[123, 234, 345, 456] 将是我想要的。这实际上只是如何查看 ACS_TRCT 的值是否已经在我所追求的数组中的语法。
  • 循环中的其他常量呢?价值观不同吗?

标签: javascript arrays if-statement operators


【解决方案1】:

你能试试这个代码吗

    var ctids = []
    for (var i=0;i<results.features.length;i++){
          ACS_BG = results.features[i].attributes.BLKGRPCE;
          ACS_ST = results.features[i].attributes.STATEFP;
          ACS_CNTY = results.features[i].attributes.COUNTYFP;
          ACS_TRCT = results.features[i].attributes.TRACTCE;

          if(!ctids.includes(ACS_TRCT))
          {
             ctids.push(ACS_TRCT);
          }
};

【讨论】:

  • 这在整个代码中正常工作,并且也无需使用{ continue; }。谢谢。
【解决方案2】:

您可以使用包含检查元素是否存在于数组中,如果不存在则将元素推入其中。

if (ctids.includes(ACS_TRCT)){
continue;
}else{
ctids.push(ACS_TRCT)
}

【讨论】:

  • 这很好用。我实际上实施了几个答案的解决方案;这与您的相同,但消除了对{ continue; } 的需要,我认为在我考虑之后只是多余的。谢谢。
【解决方案3】:

我愿意:

for (var i = 0; i < results.features.length; i++) {
  const ACS_BG = results.features[i].attributes.BLKGRPCE;
  const ACS_ST = results.features[i].attributes.STATEFP;
  const ACS_CNTY = results.features[i].attributes.COUNTYFP;
  const ACS_TRCT = results.features[i].attributes.TRACTCE;

  // push ACS_TRCT, ACS_ST, ACS_TRCT, ACS_CNTY to resulting
  // array ctids if they don't present using `.includes` method.
  if (!ctids.includes(ACS_TRCT)) ctids.push(ACS_TRCT);
  if (!ctids.includes(ACS_ST)) ctids.push(ACS_ST);
  if (!ctids.includes(ACS_CNTY)) ctids.push(ACS_CNTY);
  if (!ctids.includes(ACS_TRCT)) ctids.push(ACS_TRCT);
}

【讨论】:

  • 请说明您这样做的原因。
  • @NinaScholz 我找到了代码,并且使用了非常易读的方法。所以我跳过了cmets。无论如何添加。
  • 嘿@ArupRakshit。这可行,但我实际上不需要将任何其他值推送到数组中。谢谢。
  • @gwydion93 好的.. 然后删除那些行.. 我正在展示模式。
【解决方案4】:

您可以使用.find 来检查该项目是否已存在于数组中(仅适用于原始类型)

var found = ctids.find(function(value) {
    return ACS_TRCT === value;
});

if(!found) {
    ctids.push(ACS_TRCT);
}

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2019-08-20
    相关资源
    最近更新 更多