js中includes与indexof区别
时间: 2023-11-04 12:20:20 浏览: 37
在JavaScript中,includes和indexOf是用于不同类型的数据结构的方法。
- includes方法用于数组,用于判断一个数组是否包含指定的值。如果数组中包含该值,则返回true;否则返回false。这个方法可以判断数组中是否包含NaN这样的特殊值。例如,对于数组`const arr = ['a','b',NaN]`,`arr.includes(NaN)`返回true,而`arr.includes('c')`返回false。
- indexOf方法用于字符串和数组,用于判断一个字符串或数组中是否包含另一个字符串或值。如果存在,则返回该字符串或值的第一个索引。如果不存在,则返回-1。例如,对于字符串`var arr='asdfg'`,`arr.indexOf('s')`返回1。对于数组`const arr = ['a','b']`,`arr.indexOf('a')`返回0。
因此,includes方法主要用于判断数组中是否包含指定的值,而indexOf方法主要用于查找字符串或数组中是否包含另一个字符串或值,并返回它的索引。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [js 中 includes和indexOf的区别](https://blog.csdn.net/xiasohuai/article/details/122828976)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [indexof、includes、starstWith、endsWith的区别](https://download.csdn.net/download/weixin_38693528/14045234)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]