What is the includes() method?
The first parameter is the element that we want to search for in the array or string. The second parameter is an optional parameter that specifies the starting index for the search.
Using includes() with arrays
The includes() method provides an easy and efficient way to determine whether or not an element is present in an array. For example, if we have an array of numbers, we can use the includes() method to check if a specific number is present in the array.
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false
The above code will return true as the number 3 is present in the array. On the other hand, the code will return false as the number 6 is not present in the array.
Using includes() with strings
The includes() method can also be used with strings to check if a specific character or substring exists in a string. This can be useful when working with text-based applications or dealing with user inputs. For example:
const message = 'Hello World';
console.log(message.includes('o')); // true
The above code will return true as the letter 'o' exists in the string 'Hello World'.
The benefits of using includes()
The includes() method provides many benefits and advantages for developers. Some of the advantages are listed below:
The includes() method is easy to use and understand.
The includes() method is efficient and does not require a loop to search for elements.
The includes() method is case-sensitive and can distinguish between uppercase and lowercase letters.
The includes() method is supported by most modern web browsers.
- 2023-08-12js splice删除(数组修改方法，精简代码)
- 2023-09-28js sessionstorage(用sessionStorage存储浏览器数据)