JavaScript 的 indexOf 及其作用;

129 阅读1分钟

javaScript 的indexOf 方法;

   indexOf() 方法可返回某个指定的字符串在字符串中首次出现的位置,如果没有找到匹配的字符串,则返回-1
    let str = 'I hope the COVID-19 pandemic will pass soon.';
    str.indexOf('COVID-19'); // 11
    str.indexOf('covid-19'); // -1
    // *** indexOf 时区分大小写的;
    indexOf() 有第二个的参数,为number,这个参数标记了 在字符串中开始检索的位置;
    let str = 'I hope the COVID-19 pandemic will pass soon.';
    str.indexOf('COVID-19', 11); // 0

indexOf 与 for 循环一起使用,可以 删除重复值;

    const array = [56,23,21,12,109,66,21,66]; array.filter((item,idx,arr) => arr.indexOf(item) === idx);