Arrays and strings are frequently manipulated, especially by interception. The names of some of the string and array operations are the same, so that there is not always confusion, summarized for reference.

String manipulation

Cut merge intercept

split

Function: string.split (separator,? limit)

Function: Splits a string into an array using a specified separator

const str = 'jpg|bmp|gif|ico|png';
let arr = str.split('|'); // [jpg, bmp, gif, ico, png]
let arr = str.split('|'.2); // [JPG, BMP] - The second argument limits the size of the array
Copy the code

concat

Function: String concat (... strings)

Function: Place multiple strings in sequence after a String

'start'.concat(', '.'hello'.' world') // start, hello world
Copy the code

Slice, substring, substr

Function: String. Slice (? start, ? end)

  • Start: Optional. Specifies the start position of the substring. Default is 0. It could be negative, -1 for the last digit, -2 for the second to last digit.
  • End: Optional. Specifies the end position of the substring, which can be negative. If this parameter is not specified, it represents the substring from start to the end of the string.
  • Return: Returns a substring containing all characters from start to end-1. The length is end-start.

Function: string. substring(start,? end)

  • Start: Mandatory. A non-negative integer that specifies the start of a substring. If start is negative, it is automatically replaced with 0
  • End: Optional. A non-negative integer that specifies the end position of the substring. If end is negative, it is automatically replaced with 0
  • Return: Returns a substring containing all characters from start to end-1. The length is end-start.

If start is larger than end, two arguments are exchanged before the string is truncated

Function: string. substr(from,? length)

  • From: Mandatory. Specifies the start position of the substring. It could be negative, -1 for the last digit, -2 for the second to last digit.
  • Length: Optional. Length of the string to be selected. 0 or negative returns an empty string. If not specified, the substring continues to the end of the string.
  • Return: Returns a substring containing the length of the string truncated from start.
'012345'.slice() / / 012345
'012345'.substring() / / 012345
'012345'.substr() / / 012345

'012345'.slice(1) / / 12345
'012345'.substring(1) / / 12345
'012345'.substr(1) / / 12345

'012345'.slice(-2) / / 45
'012345'.substring(-2) / / 012345 | * negative replacement is 0, become the substring (0)
'012345'.substr(-2) / / 45

'012345'.slice(1.3) / / 12 | * position 1 to 3-1 string
'012345'.substring(1.3) / / 12 | * position 1 to 3-1 string
'012345'.substr(1.3) / / 123 | * length from 1 to 3 of the string

'012345'.slice(3.1) / / '| * from position 3 to 1, not intercept characters
'012345'.substring(3.1) / / 12 | * start and end swaps, become the substring (1, 3)
'012345'.substr(3.1) / / 3 | * from position 3 interception, the length of 1

'012345'.slice(-3, -1) / / 34 | * third from bottom to 1 (the bottom - 1) string
'012345'.substring(-3, -1) / / '| * negative replacement is 0, become the substring (0, 0)
'012345'.substr(-3, -1) / / '| * length is negative, there is no length, returns an empty string
Copy the code

Summary:

  1. slice.substringIntercepting strings by position;substrCut by length.
  2. substringthestart/endIs a non-negative integer,slicethestart/end.substrthefromIt could be negative.
  3. The second argument does not provide (end.length), intercepts to the end of the string.
  4. onlysubstringIt automatically adjusts according to the sizestart, endTo intercept a valid string.

To find the replacement

IndexOf, lastIndexOf

Function: string.indexof (searchString,? position), String.lastIndexOf(searchString, ? IndexOf looks backwards from the beginning of the string to the position of the specified string. LastIndexOf, in contrast, looks forwards from the end of the string

  • SearchString: The string to find
  • Position: Searches from this position, not from the beginning or end position. A non-negative integer.
  • Return: Returns the positional index if the string is found, -1 otherwise
'hello world'.indexOf('o') / / 4
'hello world'.indexOf('o'.5) / / 7 | * from space (index = 5) began to find back
'hello world'.lastIndexOf('o'.7) / / 7
'hello world'.lastIndexOf('o'.5) / / 4 | * from space (index = 5) began to look ahead
Copy the code

charAt

Function: String. CharAt (index)

Function: Returns a character at a specified position. The subscript of the first character in the string is 0. If the index argument is not between 0 and String.length, the method returns an empty string.

  • Index: this parameter is optional. The default value is 0. The value is a non-negative integer.
'0123456'.charAt(4) / / 4
'0123456'.charAt(10) / /"
Copy the code

charCodeAt

Function: String. CharCodeAt (index) Function: Returns the Unicode encoding of a character at a specified position. The return value is an integer between 0 and 65535. If the index argument is not between 0 and String.length, the method returns NaN(an empty string cannot be converted to a digit because no string was found).

'0123456'.charCodeAt(4) / / 52
'0123456'.charCodeAt(-1) // NaN
'0123456'.charCodeAt(10) // NaN
Copy the code

replace

Function: String.replace(searchValue, replaceValue)

  • SearchValue: The string to be replaced, which can be a regular expression
  • ReplaceValue: indicates the replacement string
'bone, alone, phone'.replace('one'.1) // b1, alone, phone
'bone, alone, phone'.replace(/one/g.1) // b1, al1, ph1
Copy the code

trim

Function: string.trim () Function: Trim the beginning and end of a String

Trim is defined in ES5 and supported by most browsers, so you no longer need to implement it yourself. For details, see Trim on MDN

' hello '.trim() // 'hello'
Copy the code

Array manipulation

Array global operation

join

Function: Array. Join (? separator)

Function: Merges array entries into a string using the specified delimiter, default to “,” if no argument is passed

const arr = ['jpg'.'bmp'.'gif'.'ico'.'png']
let str = arr.join('|') // jpg|bmp|gif|ico|png
Copy the code

reverse

Function: Reversing the order of function entries changes the original array

const ary = [1.2.3]
ary.reverse()
console.log(ary) / / [3, 2, 1]
Copy the code

concat

Function: Combine multiple arrays without changing the original array

const ary = ['cat']
const newary = ary.concat(['hat'], ['bat'.'fat'])
console.log(newary) // ["cat", "hat", "bat", "fat"]
Copy the code

Array entry operation

indexOf, lastIndexOf

Function: indexOf finds the first matched item index from front to back. LastIndexOf does the opposite

const ary = ["cat"."hat"."cat"."fat"]
const index = ary.indexOf('cat') / / 0
const lastIndex = ary.lastIndexOf('cat') / / 2
Copy the code

push

Function: Insert an item at the end of an array, changing the original array. The return value is the inserted array length.

const ary = ['head'.'tail']
const length = ary.push('hello')
console.log(ary) // ['head', 'tail', 'hello']
console.log(length) / / 3
Copy the code

pop

Function: Removing an item from the end of an array changes the original array. The return value is the removed item.

const ary = ['head'.'tail']
const item = ary.pop()
console.log(ary) // ['head']
console.log(item) // 'tail'
Copy the code

unshift

Function: Insert an item into the header of an array that changes the original array. The return value is the inserted array length.

const ary = ['head'.'tail']
const length = ary.unshift('hello')
console.log(ary) // ['hello', 'head', 'tail']
console.log(length) / / 3
Copy the code

shift

Function: Removing an item from the array header changes the array. The return value is the removed item.

const ary = ['head'.'tail']
const item = ary.shift()
console.log(ary) // ['tail']
console.log(item) // 'head'
Copy the code

slice

Function: Array. Slice (? start, ? end)

Function: array item interception, generate sub-array.

  • Start: Optional. Specifies the starting position of an array element. Default is 0. It could be negative, -1 for the last digit, -2 for the second to last digit.
  • End: Optional. Specifies the end position of a subarray element, which can be negative. If this parameter is not specified, it represents the substring from start to the end of the string.
  • Return: Returns a substring containing all elements from start to end-1. The array length is end-start.
const ary1 = [0.1.2.3.4.5].slice() / /,1,2,3,4,5 [0]
const ary2 = [0.1.2.3.4.5].slice(3) / / / three, four, five
const ary3 = [0.1.2.3.4.5].slice(3.5) / / [3, 4]
const ary4 = [0.1.2.3.4.5].slice(3, -1) / / [3, 4] | * end = 1 + 6 = 5, last the first item
const ary5 = [0.1.2.3.4.5].slice(-2, -1) / / [4]
Copy the code

splice

Function: array.splice (start,? deleteCount, ... items)

Function: can be added to the array delete, indirect replacement function. It changes the original array.

  • Start: start operation index (the starting position of an item to be deleted or added, including the item to be deleted)
  • DeleteCount: The number of items to be deleted starting from start, a non-negative integer. If not specified, all entries from start to the end of the array are deleted
  • Items: Array items to add. You can have multiple items
  • Return: Returns an array of deleted elements
let ary = [0.1.2.3.4.5]
let res = ary.splice(2) // From position 2, delete all items backwards
console.log(ary, res) // ary = [0, 1], res = [2, 3, 4, 5]

ary = [0.1.2.3.4.5]
res = ary.splice(2.1) // Delete one item from position 2
console.log(ary, res) // ary = [0, 1, 3, 4, 5], res = [2]

ary = [0.1.2.3.4.5]
res = ary.splice(2.3) // Delete three items from position 2
console.log(ary, res) // ary = [0, 1, 5], res = [2, 3, 4]

ary = [0.1.2.3.4.5]
res = ary.splice(2.1.'hello') // Delete one item from 2 and add one item at 2.
console.log(ary, res) // ary = [0, 1, 'hello', 3, 4, 5], res = [2]

ary = [0.1.2.3.4.5]
res = ary.splice(2.3.'hello') // Delete three items from position 2 and add one item at position 2
console.log(ary, res) // ary = [0, 1, 'hello', 5], res = [2, 3, 4]

ary = [0.1.2.3.4.5]
res = ary.splice(2.1.'hello'.'world') // Delete one item from position 2 and add several items in sequence at position 2
console.log(ary, res) // ary = [0, 1, 'hello', 'world', 3, 4, 5], res = [2]

ary = [0.1.2.3.4.5]
res = ary.splice(2.3.'hello'.'world') // Delete three items from position 2 and add more items in sequence at position 2
console.log(ary, res) // ary = [0, 1, 'hello', 'world', 5], res = [2, 3, 4]
Copy the code

The iterative operation

sort

Function: Sort an array item by its Unicode character. If it is not a string, call toString to convert it to a string.

const ary = [1.2.10.3]
ary.sort()
console.log(ary) / / [1, 10, 2, 3] | * 10 into the string '10'
Copy the code

forEach

Function: array traversal

['a'.'b'.'c'].forEach(function(item, index, array) {
    console.log(item, index, array)
    // a 0 ['a', 'b', 'c'];
    // b 1 ['a', 'b', 'c']; 
    // c 2 ['a', 'b', 'c'];
})
Copy the code

map

Function: Iterate over items in a number group, and return the array of items processed

const ary = ['a'.'b'.'c'].map(function(item, index, ary) {
  return item.charCodeAt(0)})console.log(ary) / / [97, 98, 99]
Copy the code

filter

Function: Iterate over the number group items, and return the array of items that meet the conditions

const ary = [1.2.3.10.21].map(function(item, index, ary) {
  return item < 10
})
console.log(ary) / / [1, 2, 3]
Copy the code

every, some

Function:

  • Every: returns true if each item of a group meets the condition, and false otherwise
  • Some: Iterates through the list of items, returning true once an item is found, stopping iterating, and false otherwise
let res = [1.2.3.10.21].every(function(item, index, ary) {
 	return item < 100
})
console.log(res) // true

res = [1.2.3.10.21].some(function(item, index, ary) {
	console.log(item) // 1 is executed only once
 	return item < 100
})
console.log(res) // true

res = [1.2.3.10.21].some(function(item, index, ary) {
	console.log(item) // 1, 2, 3, 10, 21
 	return item > 100
})
console.log(res) // false
Copy the code

reduce, reduceRight

Reduce (function(total, currentValue, currentIndex, ARR), initialValue)

Function: aggregate array items, according to the aggregate function to generate the final result. Reduce starts from the first element and aggregates from left to right, while reduceRight is the opposite

let res = [1.2.3.4.5].reduce(function(a, b) {
  return a + b
})
console.log(res) // 1 + 2 + 3 + 4 + 5 = 15

res = [1.2.3.4.5].reduce(function(a, b) {
  return a + b
}, 10) / / initial value
console.log(res) // 10 + 1 + 2 + 3 + 4 + 5 = 25

res = [1.2.3.4.5].reduce(function(a, b) {
  return a - b
})
console.log(res) // 1-2-3-4-5 = -13

res = [1.2.3.4.5].reduceRight(function(a, b) {
  return a - b
})
console.log(res) // 5-4-3-2-1 = -1

res = [1.2.3.4.5].reduceRight(function(a, b) {
  return a - b
}, 1) / / initial value
console.log(res) // 1-5-4-3-2-1 = -1
Copy the code

summary

  • Operations that change the original array:reverse.sort.splice.push.pop.shift.unshift

String and array operations with the same name

slice

const str = '012345'.slice(1.3) / / '12'
const ary = [0.1.2.3.4.5].slice(1.3) / / [1, 2]
Copy the code

concat

const str = 'start'.concat(', '.'hello'.' world') // start, hello world
const ary = ['start'].concat([', '.' hello'], ['world']) // ['start', ',', ' hello', 'world']
Copy the code

indexOf, lastIndexOf

const index1 = 'hello world'.indexOf('o') / / 4
const index2 = ['hello'.'world'].indexOf('world') / / 1
const index3 = 'hello world'.lastIndexOf('o') / / 7
const index4 = ['hello'.'world'].lastIndexOf('world') / / 1
Copy the code