indexOf in Ruby

10

想知道JavaScript中是否有类似于indexOf的Array对象方法?

例如:

arr = %w{'a', 'b', 'c'}
c = 'c'
if (arr.indexOf(c) != -1)
// 做一些事情
else
// 不做一些事情
4个回答

14

编辑你的回答(http://stackoverflow.com/questions/12617036/ruby-why-arr-wa-b-c-a-b-c/12617106#12617106),如果正确将获得一个积分。 - Jackie Chan
@DanMyasnikov 我刚刚使用了你问题中的 arr,是的,'c' 不在你的数组中,但 "'c'" 在其中。 - xdazz

4

如果你想检查数组中是否存在某个元素,可以使用include?方法:

if arr.include?(c)
  # do stuff
else 
  # don’t
end

2
使用 Array#index 进行操作:
c = 'c'
%w{a b c}.index(c)

我认为你的意思是写成 %w{a b c} - waldrumpus
@waldrumpus 是的,谢谢,从问题中复制粘贴的源代码。 - Hck
所以你做了 - 抱歉,我应该在上面发布评论。 - waldrumpus

0
if arr.last == c
  # do some stuff
else
  # don't do some stuff
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接