【问题标题】:Array iteration in javascriptjavascript中的数组迭代
【发布时间】:2018-05-14 18:36:14
【问题描述】:
Array: {3412124539: 1, 3412124540: 1, 3412124577: 2, 3412124590: 1, 3412124602: 1, 3412124605: 1, 3412124607: 1, 3412124617: 1, 3412124629: 1, 3412124630: 1, 4709502367: 1, 4709502349: 1, 4709502326: 1, 4708510268: 1, 4708510060: 1, …}

我想搜索3412124577。 如果值为2 然后返回。

我该怎么做。此外,当我尝试迭代 Array[30] 时。它给了我错误。 我应该如何进行搜索。

【问题讨论】:

  • 是数组还是对象?
  • 这不是数组这是对象
  • 显示代码...
  • 我使用了 _UNIQUEARRAY = _.countBy(all, "wellUid");
  • @RahulJain 然后就做_UNIQUEARRAY[3412124577]?

标签: javascript arrays


【解决方案1】:

所以我知道您在帖子中谈论的是数组,但您给我们的“数组”实际上是一个对象。令人震惊的是,我知道...注意数组 [ ] vs object { } 括号。

但在你的情况下,这实际上并不是一件坏事。您根本不需要遍历数组中的所有项目!让我给你看看。

您可以在 javascript 中通过数组表示法访问对象的键。 (还在关注?)这样做的基本方法是:

object['key']           //accessing by array notation

object.key              //accesing by dot notation

既然你在谈论返回,我假设你在谈论函数。看看下面的搜索功能,使用数组表示法检查名为集合的对象

var collection = {3412124539: 1, 3412124540: 1, 3412124577: 2, 3412124590: 1, 3412124602: 1, 3412124605: 1, 3412124607: 1, 3412124617: 1, 3412124629: 1, 3412124630: 1, 4709502367: 1, 4709502349: 1, 4709502326: 1, 4708510268: 1, 4708510060: 1}

function search(inWhat, forWhat, equalsWhat){
  if(inWhat[forWhat] == equalsWhat)
    return 'returned cause '+forWhat+' is '+equalsWhat;
}

var returnValue = search(collection, 3412124577, 2);

// ---- outputting the returnValue here
document.write(returnValue);

【讨论】:

    【解决方案2】:

    也许它可能会起作用。

    $.each(yourVariableHere, function( index, value ) {
        if(index == 2){
             console.log("I found it.");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-03-14
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2018-04-06
      • 2019-02-27
      • 2017-12-17
      相关资源
      最近更新 更多