The use of indexOf() method in JS

At work, the indexOf() method is still used very frequently. Let’s make a brief summary of this knowledge point. 

Basic definition : The indexOf() method returns the position where a specified string value first appears in the string. If it is not found, it returns -1.

- indexOf() only returns the first occurrence of a string in the specified search order

- Working application => If the string value to be retrieved is not present, the method returns -1

- The indexOf() method is case-sensitive!

1. Grammar

stringObject.indexOf(searchvalue,fromindex)

// 该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。
// 开始检索的位置在字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。
// 如果找到一个 searchvalue,则返回 searchvalue 的第一次出现的位置。
// stringObject 中的字符位置是从 0 开始的

2. Specific application of indexOf() method in arrays and strings

This method returns the position of an element in a string or array.

<1> Use in String type objects
let str = 'orange';
 
str.indexOf('o'); //0
str.indexOf('n'); //3
str.indexOf('c'); //-1  未找到返回-1

Note: JavaScript String indexOf() method 

<2> Use in Array type objects

array.indexOf(item,start)
returns the position of the element in the array. If it is not retrieved, it returns -1.
Parameter description
item is required. The element to find
start is optional. Specifies the location to be retrieved. Its legal values ​​are 0 to stringObject.length - 1.

To find elements in an array, you can also use the find() method provided in ES6

let arr = ['orange', '2016', '2016'];
 
arr.indexOf('orange'); //0
arr.indexOf('o'); //-1

var arr = [1,2,3];
console.log(arr.indexOf('1'));//-1 不包含 从这可以看出数组使用indexOf区分类型(type)
console.log(arr.indexOf(1));//0 包含
console.log(arr.indexOf(2));//1 包含
console.log(arr.indexOf(3));//2 包含
console.log(arr.indexOf(4));//-1 不包含

<3> Cannot be used for Number type

let num = 2016;
 
num.indexOf(2); //Uncaught TypeError: num.indexOf is not a function

Do I have to use the indexOf method for number type? Then convert it into a string, and then write the above example

// 二逼青年的写法
num = '2016';
num.indexOf(2); //0
 
// 普通青年的写法
num.toString().indexOf(2); //0
 
// 文艺青年的写法
('' + num).indexOf(2); //0

3. Use indexOf() to deduplicate the array

// 写法一
var newArr =  [ ];

arr.forEach(function(v){ // 使用forEach循环遍历,获取原始数组arr中的所有数值
            // 在新数组中,查找当前获取的原始数组的数值
            // newArr.indexOf(v) 执行结果如果是 -1
            // 证明在新数组中,没有这个原始数组的数据
    if(newArr.indexOf(v) === -1){
           // 将这个数据,写入到新数组中
           newArr.push(v)
    }
})
console.log( newArr );

// 写法二 
var arr = ['C','A','A','G','G','G','D']
var newArr = []

arr = arr.sort().forEach(function(n){
            if(newArr.indexOf(n) == -1){
               newArr.push(n)
            }
         })
console.log(newArr);// ["A", "C", "D", "G"]

// 写法三
var arr = ['a','c','b','d','a','b']
var arr2 = [];

for(var i = 0;i<arr.length;i++){
    if(arr2.indexOf(arr[i])<0){
       arr2.push(arr[i]);
    }
}
arr2.sort();
console.log(arr2);//["a", "b", "c", "d"]
  

Extra: sort() method   sort() method in JS JavaScript sort() method | Newbie tutorial Comprehensive understanding of the sort() method that comes with JS | Script Home  

The sort() method is used to sort the elements of an array. The sort order can be alphabetical or numerical, and in ascending or descending order. The default sort order is ascending alphabetically.

NOTE: This approach will mutate the original array!

grammar:

arrayObject.sort(sortby); the parameter sortby is optional. Specifies the sort order. Must be a function;

The sort() method of Array converts all elements to String by default and then sorts them according to Unicode.

sort() will change the original array and return the changed (sorted) array.

Note: If this method is called without parameters, the elements in the array will be sorted alphabetically, or more precisely, in character encoding order. To achieve this, the elements of the array should first be converted to strings (if necessary) for comparison.

If you want to sort by other criteria, you need to provide a comparison function that compares two values ​​and returns a number that describes the relative order of the two values. The comparison function should have two parameters a and b (a represents the next comparison number of the current comparison number, and b represents the current comparison number) :

The comparison function should have two parameters a and b and its return value is as follows:

If a is less than b, that is, a - b is less than zero, a should appear before b in the sorted array, then a value less than 0 will be returned, and the array will be sorted in ascending order.

If a equals b, then 0 is returned.

If a is greater than b, that is, a - b is greater than zero, a value greater than 0 will be returned, and the array will be sorted in descending order.

Ascending

Sort descending 


4. Comparison between findIndex and indexOf of JS array

<1> findIndex()

The findIndex() method returns the position of the first element of the array passed in a test condition (function) that meets the condition.

The findIndex() method calls a function execution once for each element in the array:

When an element in the array returns true when testing a condition, findIndex() returns the index position of the element that meets the condition, and subsequent values ​​will not call the execution function.

If there is no matching element, return -1

Note: The findIndex() function will not be executed for an empty array.

Note:  findIndex() does not change the original value of the array.

Reference article : Summary of ES6 array methods find(), findIndex() and filter() - short book

<2> indexOf()

The indexOf() method returns the position of a specified element in an array.

This method will search the array from beginning to end to see if it contains the corresponding element. The position to start retrieval is at array start or at the beginning of the array (when the start parameter is not specified). If an item is found, the position of the first occurrence of the item is returned. The index of the starting position is 0.

Returns -1 if the specified element is not found in the array.

✔ Comparison between findIndex() and indexOf() ✔

1. The findIndex() and indexOf() methods are implemented through loop traversal.

2. The application scenarios of findIndex() are wider than indexOf(). It can search for greater than equal to less than. The expression can be written casually, but indexOf can only find equal values ​​in the first level.

3. findIndex() is actually equivalent to a for loop, except that you don’t need to exit yourself after it is found.


References

JS advanced regular related functions and regular objects-CSDN Blog

The use and precautions of indexOf and the use of indexOf for arrays

Introduction to JavaScript indexOf - Zhihu  |  Tips on using indexOf in javaScript - Script Home

Guess you like

Origin blog.csdn.net/sunyctf/article/details/135269738