str的indexOf怎么用?

424 阅读1分钟

chat-gpt的回答😊

JavaScript中的indexOf方法用于返回字符串中指定子字符串的第一个匹配索引。它的语法如下:

str.indexOf(searchValue, fromIndex)
  • searchValue: 要搜索的子字符串。
  • fromIndex (可选): 从 str 的指定索引位置开始搜索。如果不提供该参数,则默认从索引位置0开始搜索。

indexOf方法返回搜索到的第一个匹配的索引值,如果未找到匹配的子字符串,则返回-1。

下面是一个例子:

let str = "Hello, world!";
let index = str.indexOf("world");
console.log(index);  // 输出: 7

在这个例子中,indexOf方法搜索字符串str中的子字符串"world",找到它在索引位置7出现的第一个匹配。

同时,你还可以传递第二个参数来指定搜索的起始索引位置。例如:

let str = "Hello, world!";
let index = str.indexOf("o", 5);
console.log(index);  // 输出: 8

在这个例子中,indexOf方法从索引位置5开始搜索字符串str中的子字符串"o",找到它在索引位置8出现的第一个匹配。

我的回答🙂

用的比较多的是用来在字符串数组中的去重操作

 getAv(attr, av) {
      console.log(attr, av);
      let props = `${attr.attrId}:${av}:${attr.attrName}`;
      if (this.searchParams.props.indexOf(props) == -1) {
        this.searchParams.props.push(props);
        this.$store.dispatch("searchList");
      }
    },
    //以上代码是一个判断数组中有没有当前字符串的操作,如果有则不会进行push和dispatch操作,如果没有才执行,判断条件等于-1则表示没有这个字符串,如果不等于-1则表示含有这个字符串
    

当然这个去重操作并不是只能用这一种判断条件,这只是其中的一种,希望能解答到你的问题!如果还有其他疑问,请随时问我。