Comparison of Array and String Methods in javascript

  • 2021-07-04 17:50:07
  • OfStack

Previous words

Strings and arrays have many similarities, their methods are numerous, and the similarity is very high; However, they are different. Strings are immutable values, so they can be regarded as read-only arrays. This article will compare similar methods of strings and arrays

Indexable

ECMAScript5 defines a method of accessing characters, using square brackets and numeric indexes to access specific characters in strings

The biggest advantage of indexable strings is simplicity, with square brackets instead of the charAt () call, which is more concise, readable, and possibly more efficient. Moreover, the fact that strings behave like arrays allows generic array methods to be applied to strings

Output undefined if the parameter is out of range or NaN


var str = "hello";
console.log(str[0]);//h
console.log(str[[1]]);//e

console.log(str[false]);//undefined
console.log(str[-1]);//undefined
console.log(str[NaN]);//undefined
console.log(str[]);// Report an error 

var arr = ['h','e','l','l','o'];
console.log(arr[0]);//h
console.log(arr[[1]]);//e

console.log(arr[false]);//undefined
console.log(arr[-1]);//undefined
console.log(arr[NaN]);//undefined
console.log(arr[]);// Report an error 

Conversion

Strings can be converted to arrays using the split () method; Arrays can be converted to strings using the join () method

"split ()"

The split () method divides a string into multiple strings based on the specified delimiter, which can be either a string or a regular expression, and places the result in an array

This method can accept the (optional) second parameter to specify the size of the array. If the second parameter is in the range of 0-array. length, output according to the specified parameter, otherwise all results will be output

Returns the value of the original string as an array if the specified delimiter does not appear in the string


var colorText = 'red,blue,green,yellow';
console.log(colorText.split(''));//["r", "e", "d", ",", "b", "l", "u", "e", ",", "g", "r", "e", "e", "n", ",", "y", "e", "l", "l", "o", "w"]
console.log(colorText.split(','));//["red", "blue", "green", "yellow"]
console.log(colorText.split(',',2));//["red", "blue"]
console.log(colorText.split(',',6));//["red", "blue", "green", "yellow"]
console.log(colorText.split('-'));//["red,blue,green,yellow"]
console.log(colorText.split(/\,/));//["red", "blue", "green", "yellow"]
console.log(colorText.split(/e/));//["r", "d,blu", ",gr", "", "n,y", "llow"]
console.log(colorText.split(/[^\,]+/));// Change strings other than commas into delimiters ["", ",", ",", ",", ""],IE8- Will be recognized as [",",",",","]

"join ()"

The join () method can use different delimiters to construct this string, and the join () method takes only one parameter, the string used as the delimiter, and then returns the string containing all the array items

If no value is passed to the join () method, a comma is used as the separator


var a = [1,2,3];
console.log(a.join());//'1,2,3'
console.log(a.join(' '));//'1 2 3'
console.log(a.join(''));//'123'

var b = new Array(10);
b.join('-');//'---------' , 9 A string consisting of three hyphens 

If the value of an item 1 in the array is null or undefined, the value is represented as an empty string in the result returned by the join () method


var colors = [1,undefined,2,null,3];
console.log(colors.join());//'1,,2,,3'

Because the string is an array-like object, you can also use the join () method


console.log(Array.prototype.join.call('hello', '-'));// "h-e-l-l-o"

var str = 'test';
var arr = str.split('')//["t", "e", "s", "t"]
console.log(arr.join('-'));//'t-e-s-t'

Splice

Strings and arrays share the splicing method concat ()


var value = 'hello';
console.log(value.concat('world'));//'helloworld'
console.log(value.concat(['world']));//'helloworld'
console.log(value.concat([['world']]));//'helloworld'

var value = ['hello'];
console.log(value.concat('world'));//["hello", "world"]
console.log(value.concat(['world']));//["hello", "world"]
console.log(value.concat([['world']]));//["hello", ["world"]]

Create

Both strings and arrays have the creation method slice (), which is used to create substrings and subarrays, respectively

The slice () method creates a new array (or string) based on one or more items in the current array (or string), accepts one or two parameters, that is, the starting and ending positions of the items to be returned, and finally returns the new array (or string)

The slice (start, end) method requires two parameters, start and end, and returns one subarray (or string) of the array (or string) from the start position to (but not) the end position; If end is undefined or does not exist, all entries from the start position to the end of the array (or string) are returned

If start is negative, start = max (length + start, 0)

If end is negative, end = max (length + end, 0)

start and end cannot swap locations


var numbers = [1,2,3,4,5];
console.log(numbers.slice(2));//[3,4,5]
console.log(numbers.slice(2,undefined));//[3,4,5]
console.log(numbers.slice(2,3));//[3]
console.log(numbers.slice(2,1));//[]

console.log(numbers.slice(-3));//-3+5=2 -> [3,4,5]
console.log(numbers.slice(-8));//max(5 + -8,0)=0 -> [1,2,3,4,5]

console.log(numbers.slice(0,-3));//-3+5=2 -> [1,2]
console.log(numbers.slice(-2,-1));//-2+5=3;-1+5=4; -> [4]

var arr = ['h','e','l','l','o'];
console.log(arr[0]);//h
console.log(arr[[1]]);//e

console.log(arr[false]);//undefined
console.log(arr[-1]);//undefined
console.log(arr[NaN]);//undefined
console.log(arr[]);// Report an error 
0

Position

Both strings and arrays have two ways to find positions: indexOf () and lastIndexOf (). The position method is the opposite of the bracket [] reading method, one is to find the index by item, and the other is to find the item by index

"indexOf ()"

The indexOf (search, start) method receives two parameters search and start, returns the position where search first appears, and returns-1 if it is not found

The search parameter in the string calls the String () transition function to convert the non-string value of the parameter to a string; The search parameters in the array are compared using the strict equality operator (= = =)

Whether it is an array or a string, the second parameter start implicitly calls the Number () transition function to convert the non-numeric value of start (except undefined) to a numeric value; start = 0 if the parameter is ignored or if the parameter is undefined, NaN

If the start parameter is negative, the string is processed by setting start = 0; The processing of arrays is start = max (0, start+length)


var arr = ['h','e','l','l','o'];
console.log(arr[0]);//h
console.log(arr[[1]]);//e

console.log(arr[false]);//undefined
console.log(arr[-1]);//undefined
console.log(arr[NaN]);//undefined
console.log(arr[]);// Report an error 
1

var arr = ['h','e','l','l','o'];
console.log(arr[0]);//h
console.log(arr[[1]]);//e

console.log(arr[false]);//undefined
console.log(arr[-1]);//undefined
console.log(arr[NaN]);//undefined
console.log(arr[]);// Report an error 
2

"lastIndexOf ()"

Contrary to the indexOf () method, the lastIndexOf () method looks from right to left

The lastIndexOf (search, start) method receives two parameters, search and start, returns the first occurrence of searchString, and returns-1 if it is not found

Similarly, the search parameter in a string calls the String () transition function to convert the non-string value of the parameter to a string; The search parameters in the array are compared using the strict equality operator (= = =)

Whether it is an array or a string, the second argument, start, implicitly calls the Number () transition function to convert the non-numeric value of start (except undefined) to a numeric value

If the parameter is ignored or if the parameter is undefined, NaN, the string processing is start = length-1; And the processing of arrays is start = 0

If the start parameter is negative, the string is processed by setting start=0; The processing of arrays is start = max (0, start+length)


var string = 'hello world world';
console.log(string.lastIndexOf('ld'));//15
console.log(string.lastIndexOf('ld',undefined));//15
console.log(string.lastIndexOf('ld',NaN));//15
console.log(string.lastIndexOf('ld',-1));//-1
console.log(string.lastIndexOf('h',-1));//0
console.log(string.lastIndexOf('w',undefined));//12

console.log(string.lastIndexOf('ld',10));//9
console.log(string.lastIndexOf('ld',[10]));//9
console.log(string.lastIndexOf('true',[10]));//-1
console.log(string.lastIndexOf(false,[10]));//-1

var arr = ['h','e','l','l','o'];
console.log(arr[0]);//h
console.log(arr[[1]]);//e

console.log(arr[false]);//undefined
console.log(arr[-1]);//undefined
console.log(arr[NaN]);//undefined
console.log(arr[]);// Report an error 
4

Related articles: