The previous words
Strings and arrays have many similarities. They have many methods and are very similar; but they have differences. Strings are immutable values, so they can be regarded as read-only arrays. This article compares similar methods of strings and arrays
Indexable
ECMAScript5 defines a method to access characters, using square brackets plus numeric indexes to access specific characters in a string
The biggest benefit of indexable strings is that they are simple, replacing charAt() calls with square brackets, which is more concise, readable and possibly more efficient. Not only that, the fact that strings behave like arrays makes common array methods applicable to strings
If the parameter is out of range or NaN, undefined output
var str = "hello";console.log(str[0]);//hconsole.log(str[[1]]);//econsole.log(str[false]);//undefinedconsole.log(str[-1]);//undefinedconsole.log(str[NaN]);//undefinedconsole.log(str[]);//report error
var arr = ['h','e','l','l','o'];console.log(arr[0]);//hconsole.log(arr[[1]]);//econsole.log(arr[false]);//undefinedconsole.log(arr[-1]);//undefinedconsole.log(arr[NaN]);//undefinedconsole.log(arr[]);//report error
Convert
Strings can be converted to arrays using split() method; arrays can be converted to strings using join() method
【split()】
The split() method divides a string into multiple strings based on the specified separator and places the result in an array. The separator can be a string or a regular expression
This method can accept (optional) a second parameter to specify the size of the array. If the second parameter is a value in the range 0-array.length, output according to the specified parameter, and output all results in other cases.
If the specified delimiter does not appear in the string, the value of the original string is returned as an array.
var colorText = 'red,blue,green,yellow';console.log(colorText.split(''));//["r", "e", "d", ",", "b", "l", "u", "e", "e", "e", ",", "g", "r", "e", "e", "e", "e", "n", ",", "y", "e", "l", "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,blue", ",gr", "", "n,y", "llow"]console.log(colorText.split(/[^/,]+/));//Change strings other than commas into separators ["", ",",", ",", "","], IE8- will recognize as [",",",",",","]【join()】
The join() method can use different delimiters to build this string. The join() method only receives one parameter, which is used as a delimiter, and then returns a string containing all array items.
If no value is passed to the join() method, use a comma 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('-');//'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------If the value of an item 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'
Since strings are array objects, you can also use the join() method
console.log(Array.prototype.join.call('hello', '-'));// "hello" var str = 'test';var arr = str.split('')//["t", "e", "s", "t"]console.log(arr.join('-'));//'tes-t'Splicing
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"]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, to return the start and end positions of the item, and finally return the new array (or string)
The slice(start, end) method requires two parameters start and end, which returns a subarray (or string) from the start position to (but does not contain) end position in this array (or string). If end is undefined or does not exist, it returns all items from the start position to the end of the array (or string).
If start is a negative number, start = max(length + start,0)
If end is a negative number, end = max(length + end,0)
Start and end cannot swap positions
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 stringValue = 'hello world';console.log(stringValue.slice());//'hello world'console.log(stringValue.slice(2));//'llo world'console.log(stringValue.slice(20));//''console.log(stringValue.slice(2,undefined));//'llo world'console.log(stringValue.slice(2,-5));//'llo 'console.log(stringValue.slice(2,-20));//''console.log(stringValue.slice(-2,2));//''console.log(stringValue.slice(-2,-20));//'' console.log(stringValue.slice(-2,20));//'ld'console.log(stringValue.slice(-20,2));//'he'console.log(stringValue.slice(-20,-2));//'hello wor'
Location
Both strings and arrays have two methods to find positions: indexOf() and lastIndexOf(). The position method is exactly the opposite of the brackets[] reading method. One is to find the index through the item, and the other is to find the item through the index.
【indexOf()】
IndexOf(search, start) method receives two parameters search and start, returning the location where the search first appears, and if it is not found, it returns -1
The search parameter in a string will call the String() transformation function to convert the non-string value of the parameter into a string; while the search parameter in the array will be compared using the strict equality operator (===)
Whether it is an array or a string, the second parameter start will implicitly call the Number() transformation function, converting start non-numeric value (except undefined) into numeric values; if this parameter is ignored or the parameter is undefined or NaN, start = 0
If the start parameter is a negative number, the processing of the string is to start=0; while the processing of the array is to start = max(0, start+length)
var string = 'hello world world';console.log(string.indexOf('ld'));//9console.log(string.indexOf('ld',undefined));//9console.log(string.indexOf('ld',NaN));//9console.log(string.indexOf('ld',-1));//9console.log(string.indexOf('ld',-1));//9console.log(string.indexOf('ld',-1));//9console.log(string.indexOf('ld',-1));//9console.log(string.indexOf('ld',-1));//9console.log(string.indexOf('ld',-1));//9 console.log(string.indexOf('ld',10));//15console.log(string.indexOf('ld',[10]));//15console.log(string.indexOf('true',[10]));//-1console.log(string.indexOf(false,[10]));//-1console.log(string.indexOf(false,[10]));//-1 var arr = ['a','b','c','d','e','a','b'];console.log(arr.indexOf('a',undefined));//0console.log(arr.indexOf('a',NaN));//0console.log(arr.indexOf('a',1));//5console.log(arr.indexOf('a',true));//5console.log(arr.indexOf('a',-1));//max(0,-1+7)=6; -1console.log(arr.indexOf('a',-5));//max(0,-5+7)=2; 5console.log(arr.indexOf('a',-50));//max(0,-50+7)=0; 0【lastIndexOf()】
In contrast to the indexOf() method, the lastIndexOf() method is to look up from right to left.
The lastIndexOf(search, start) method receives two parameters search and start, returning the location where the searchString first appears, and if it is not found, it returns -1
Similarly, the search parameter in a string calls the String() transformation function to convert the non-string value of the parameter into a string; while the search parameter in the array is compared using the strict equality operator (===)
Whether it is an array or a string, the second parameter start will implicitly call the Number() transformation function, converting start non-numeric values (except undefined) into numeric values.
If this parameter is ignored or the parameter is undefined or NaN, the processing of the string is start = length - 1; while the processing of the array is start = 0
If the start parameter is a negative number, the processing of the string is to start=0; while the processing of the array is to start = max(0, start+length)
var string = 'hello world world';console.log(string.lastIndexOf('ld'));//15console.log(string.lastIndexOf('ld',undefined));//15console.log(string.lastIndexOf('ld',NaN));//15console.log(string.lastIndexOf('ld',-1));//-1console.log(string.lastIndexOf('h',-1));//0c onsole.log(string.lastIndexOf('w',undefined));//12console.log(string.lastIndexOf('ld',10));//9console.log(string.lastIndexOf('ld',[10]));//9console.log(string.lastIndexOf('ld',[10]));//-1console.log(string.lastIndexOf(false,[10]));//-1 var arr = [1,2,3,'1','2','3'];console.log(arr.lastIndexOf('2'));//4console.log(arr.lastIndexOf(3));//2console.log(arr.lastIndexOf(0));//-1var arr = ['a','b','c','d','e','a','b'];console.log(arr.lastIndexOf('b'));//6console.log(arr.lastIndexOf('b',undefined));//-1console.log(arr.lastIndexOf('a',undefined));//0console.log(arr.lastIndexOf('b',NaN));//-1console.log(arr.lastIndexOf('b',1));//1console.log(arr.lastIndexOf('b',-1));//max(0,-1+7)=6; 6console.log(arr.lastIndexOf('b',-5));//max(0,-5+7)=2; 1console.log(arr.lastIndexOf('b',-50));//max(0,-50+7)=0; -1The above comparison of arrays and string methods in JavaScript is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.