如何使用 indexOf 简化此语句?
how to simplify this statement using indexOf?
如何使用 "indexof" 简化 Javascript 中 if 语句中的以下文本?
if (a === 1 || a === 2 || a === 3) {
return "correct";
};
我猜测需要为 1、2 和 3 创建一个数组,但我不确定之后如何使用 instanceof
*编辑为 indexOf 而不是 instanceOf
The instanceof
operator tests whether an object has in its prototype chain the prototype property of a constructor.
在你的情况下,instanceof
不会帮助你。您可以将 indexOf()
与数组一起使用,如下所示。
var arr = [1, 2, 3];
// Check if a is present in the arr array
if (arr.indexOf(a) > -1) {
return "correct";
}
如何使用 "indexof" 简化 Javascript 中 if 语句中的以下文本?
if (a === 1 || a === 2 || a === 3) {
return "correct";
};
我猜测需要为 1、2 和 3 创建一个数组,但我不确定之后如何使用 instanceof
*编辑为 indexOf 而不是 instanceOf
The
instanceof
operator tests whether an object has in its prototype chain the prototype property of a constructor.
在你的情况下,instanceof
不会帮助你。您可以将 indexOf()
与数组一起使用,如下所示。
var arr = [1, 2, 3];
// Check if a is present in the arr array
if (arr.indexOf(a) > -1) {
return "correct";
}