Home  >  Article  >  Web Front-end  >  JS uses the indexOf() method to implement array deduplication

JS uses the indexOf() method to implement array deduplication

php中世界最好的语言
php中世界最好的语言Original
2018-04-17 15:13:223103browse

This time I will introduce to you how JS uses the indexOf() method to implement array deduplication, and JS uses the indexOf() method to implement array deduplication. What are the precautions? . Here is a practical case. Let’s take a look. one time.

var arr = ['abc','abcd','sss','2','d','t','2','ss','f','22','d'];
//定义一个新的数组
var s = [];
//遍历数组
for(var i = 0;i<arr.length;i++){
  if(s.indexOf(arr[i]) == -1){ //判断在s数组中是否存在,不存在则push到s数组中
    s.push(arr[i]);
  }
}
console.log(s);
//输出结果:["abc", "abcd", "sss", "2", "d", "t", "ss", "f", "22"]

The indexOf() method returns the position where a specified string value first appears in the string.

<a href="http://www.php.cn/wiki/57.html" target="_blank">string</a><a href="http://www.php.cn/wiki/60.html" target="_blank">Object</a>.indexOf(searchvalue,fromindex)

This method will search the string stringObject from beginning to end to see if it contains the substring searchvalue. The position where the search starts in the string fromindex or the beginning of the string (when fromindex is not specified). If a searchvalue is found, return searchvalue The position where it first appears. Character positions in stringObject start from 0.

Returns -1 if the string is not found in the array.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Vue cross-domain normal debugging

##Detailed explanation of the use of vue.js progressive framework

Detailed explanation of polymorphism in JS

The above is the detailed content of JS uses the indexOf() method to implement array deduplication. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn