41 lines
1.1 KiB
Plaintext
41 lines
1.1 KiB
Plaintext
Most checks against an ``indexOf`` call against a string or array compare it with -1 because 0 is a valid index. Any checks which look for values >0 ignore the first element, which is likely a bug. If you're merely checking the presence of the string, consider using ``includes`` instead. Before using ``includes`` method make sure that your browser version is supporting it.
|
||
|
||
== Noncompliant Code Example
|
||
|
||
----
|
||
var color = "blue";
|
||
var name = "ishmael";
|
||
var number = 123;
|
||
|
||
var arr = [color, name];
|
||
|
||
if (arr.indexOf("blue") > 0) { // Noncompliant
|
||
// ...
|
||
}
|
||
if (name.indexOf("ish") > 0) { // Noncompliant
|
||
// ...
|
||
}
|
||
----
|
||
|
||
== Compliant Solution
|
||
|
||
----
|
||
var color = "blue";
|
||
var name = "ishmael";
|
||
var number = 123;
|
||
|
||
var arr = [color, name];
|
||
|
||
if (arr.indexOf("blue") >= 0) {
|
||
// ...
|
||
}
|
||
if (name.includes("ish")) {
|
||
// ...
|
||
}
|
||
----
|
||
|
||
== See
|
||
|
||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes[String.prototype.includes()] documentation at MDN
|
||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes[Array.prototype.includes()] documentation at MDN
|