preface
Manipulation of strings or arrays is often involved in project development. This article summarizes the commonly used JS methods in the project, which can be quickly referred to when it is convenient to meet again.
Array common methods
1. indexOf
The indexOf() method returns the first index in the array where a given element can be found, or -1 if none exists.
const beasts = ["ant"."bison"."camel"."duck"."bison"];
console.log(beasts.indexOf("bison")); / / 1
Copy the code
You can specify the starting position: arr.indexof (searchElement[, fromIndex])
console.log(beasts.indexOf("bison".2)); / / 4
Copy the code
2. filter
The filter() method creates a new array containing all the elements of the test implemented through the provided function. The popular way of thinking about it is to find the matching elements and then filter them out and discard them.
const beasts = ["ant"."bison"."camel"."duck"."bison"];
const beasts_filter = beasts.filter((item) = > item.indexOf("bison"));
console.log(beasts_filter); // ["ant","camel","duck"]
Copy the code
3. slice
Gets the range element of the specified index array
const url_array = ["http://www"."baidu"."com"]
const url_array_slice = url_array.slice(1.2);
console.log(url_array_slice); // ["baidu"]
Copy the code
4. join
The join() method joins all the elements of an array into a string and returns the string.
const url_array = ["http://www"."baidu"."com"];
const url = url_array.join(".");
console.log(url); // "http://www.baidu.com"
Copy the code
String common methods
1. split
Splits a string into an array of strings
const url = "http://www.baidu.com";
const url_array = url.split(".");
console.log(url_array); // ["http://www","baidu","com"]
Copy the code
2. substr
String interception
const res = "helloworld";
const res_sub = res.substr(5.9);
console.log(res_sub); // "world"
Copy the code
3. parseInt
String to number parseInt(“10”)
Reference documentation
- MDN Web Docs
tool
Online debugging JS tool: CodePen