【问题标题】:Where is the string in an array? [duplicate]数组中的字符串在哪里? [复制]
【发布时间】:2012-10-02 14:00:10
【问题描述】:

可能重复:
How do I get the index of an item in an array?
search for element within an array

如果我有这样的数组:

var array = [
    "one",    //element 0
    "two",    //element 1
    "three",  //element 2
    "four",   //element 3
    "five"    //element 4
];

我想查找给定的部分,比如说five。 所以我要求代码判断five是否在array内。

如果是,那么它应该告诉我它的位置是4,或者array[4]

有什么方法可以达到类似的效果吗?

【问题讨论】:

  • 你试过什么?您是否尝试过自己寻找答案?这不是一个不寻常的情况,并且有专门设计的方法来处理这种情况。
  • indexOf 是你想要的
  • @user1689607 有一个专门为此设计的方法在较新的浏览器上
  • 在协作问答中没有人问代码。请阅读FAQ。自己尝试并发布与您的代码相关的特定问题非常重要。

标签: javascript


【解决方案1】:

array.indexOf()

如果您使用的是旧版浏览器,请使用该链接中包含的 shim。

【讨论】:

  • 我会尽快接受的。
【解决方案2】:
var array = [
    "one",    //element 0
    "two",    //element 1
    "three",  //element 2
    "four",   //element 3
    "five"    //element 4
];
alert(array.indexOf("five"));

这将提醒 4,即“五”

【讨论】:

    【解决方案3】:

    使用字符串的比较函数来查看数组中是否有特定的字符串

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 2011-06-25
      • 2014-06-15
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多