具有多个参数的indexOf [英] indexOf with multiple arguments
问题描述
确定数组上的indexOf
时是否可以使用多个参数?
Is it possible to use multiple arguments when determining indexOf
on an array?
我想确定我的数组是否包含三个整数中的任何一个.在此阶段需要注意的重要一点是,该数组将仅具有一个值(如果有更多值,它将不会到达此代码块).
I want to determine if my array contains any of three integers. Important to note at this stage that the array will only have one value (if it has more, it won't reach this code block).
array.indexOf(123 || 124 || 125) === 0
因此,如果array = [123]
,那么我的indexOf
应该是0
,因此应该是true
.
So if array = [123]
then my indexOf
should be 0
and therefore true
.
如果array = [124]
,则我的indexOf
应该为0,因此应该为true
.
If array = [124]
then my indexOf
should be 0 and therefore true
.
我发现正在发生的事情是[123]
可以正常工作,但是甚至不必费心检查indexOf
的第二个或第三个参数,而只是返回false.
What I am finding is happening is [123]
works OK but it's not even bothering to check the indexOf
for the 2nd or 3rd arguments, and is just returning false.
http://codepen.io/anon/pen/WxmyGp?editors=0011
推荐答案
如果||
运算符为true,则返回左侧,否则返回右侧. 123 || 124 || 125
只是123
的意思.
The ||
operator returns the left hand side if it is true, otherwise it returns the right hand side. 123 || 124 || 125
just means 123
.
如果要测试数组中是否有多个值,则必须依次测试每个值.
If you want to test if any of multiple values are in an array, then you have to test each one in turn.
array.indexOf(123) == 0 || array.indexOf(124) == 0 || array.indexOf(125) == 0
由于您只关心数组的一个特定索引,因此您可以将整个过程放在它的头上:
Since you only care about one specific index the array, you can turn the whole thing on its head:
[123, 124, 125].indexOf(array[0]) > -1
这篇关于具有多个参数的indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!