Comparison of methods for arrays and strings in JavaScript

Source: Internet
Author: User

Previous words

Strings and arrays have many similarities, their methods are numerous, and their similarity is high, but they are different, and strings are immutable values, so you can think of them as read-only arrays. This article compares string and array similar methods

can be indexed

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

The biggest benefit of an indexed string is simplicity, which replaces the Charat () call with square brackets, which is more concise, readable, and potentially more efficient. Not only that, but the fact that the string behaves like an array makes it possible to apply a common array method to a string

If the parameter is out of range or Nan, the output undefined

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[]);//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[]);//Error

Transformation

Strings can be converted to arrays using the split () method, and arrays can be converted to strings using the Join () method

"Split ()"

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

The method can accept (optional) The second parameter to specify the size of the array. If the second parameter is a value in the range of 0-array.length, the output of the specified parameter is followed by the output of all of the results

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", ",", " G "," R "," E "," E "," N ",", "," Y "," E "," L "," L "," O "," W "]console.log (Colortext.split (', '));//[" Red "," Blue "," green "," Ye Llow "]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 (/[^\,]+/));//will remove the string other than the comma into the delimiter ["", ",", ",", "," ""],ie8-will be recognized as [",", ",", "]

"Join ()"

The join () method can use a different delimiter to construct the string, and the Join () method receives only one argument, a string used as a delimiter, and then returns a string containing all the array items

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

var a = [1,2,3];console.log (A.join ()),//' Console.log ' (A.join (')),//' 1 2 3 ' Console.log (A.join ("));//' 123 ' var b = new Array (x); B.join ('-');//'---------', a string of 9 hyphens

If the value of an item in the array is null or undefined, the value is represented by 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 a class array 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 '

Stitching

String and array co-owned stitching 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

strings and arrays have the Create Method slice (), which is used to create substrings and sub-arrays, respectively

The slice () method creates a new array (or string) based on one or more items in the current array (or string), takes one or two arguments, returns the starting and ending positions of the item, and returns the new array (or string)

The slice (Start,end) method requires two parameters, start and end, to return a subarray (or string) from the start position to (but not including) the end position in this array (or string), or if End is undefined or does not exist, Returns all items from the start position to the end of the array (or string)

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

If end is negative, 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),//' 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 '

Position

Strings and arrays have two methods for finding locations: IndexOf () and LastIndexOf (). The location method and the bracket [] Read method are the opposite, one is through the item lookup index, one is to look up an item by index

"IndexOf ()"

The IndexOf (Search,start) method receives the search and start two parameters, returns the location where search first appears, and returns 1 if none is found.

The search parameter in the string invokes a string () transformation function, converts the non-string value of the parameter to a string, and the search parameter in the array is compared using the strict equality operator (= = =)

Whether it is an array or a string, the second argument, start, implicitly calls the number () transformation function, converting the start non-numeric value (except undefined) to a value, or start = 0 if the argument is omitted or the parameter is undefined, Nan.

If the start parameter is negative, the processing of the string is start=0, and the array processing is start = max (0,start+length)

var string = ' Hello 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 '),//15console.log (String.IndexOf (' ld ', [ten]));//15console.log (String.IndexOf (' true ', [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 found from right to left

The LastIndexOf (Search,start) method receives the search and start two parameters, returns the position where the searchstring first appears, and returns 1 if not found.

Similarly, the search parameter in the string invokes a string () transformation function that converts the non-string value of the parameter to 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 argument, start, implicitly calls the number () transformation function, converting the start non-numeric value (except undefined) to a value

If this argument is omitted or the parameter is undefined, Nan, the processing of the string is start = Length-1, and the processing of the array is start = 0

If the start parameter is negative, the processing of the string is start=0, and the array processing is start = max (0,start+length)

 var string = ' Hello 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));//0console.log (String.LastIndexOf (' W ', undefined));//12console.log ( String.LastIndexOf (' ld '),//9console.log (String.LastIndexOf (' ld ', [ten]));//9console.log (String.LastIndexOf (' True ', [ten]]);//-1console.log (String.LastIndexOf (false,[10));//-1 
var arr = [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; -1

Order

Reverse

The reverse () method exists in an array of arrays to reverse the array

var array = [1,2,4,3,5];console.log (Array,array.reverse ());//[5,3,4,2,1] [5,3,4,2,1]

String strings can also be reversed by using call () or apply ()

var str = ' 12435 '; Console.log (str,array.prototype.reverse.apply (Str.split (")). Join ("));//' 12435 ' 53421 '

Sort

The sort () method exists in an array of arrays to sort the array by default in ascending order by string

var array = [1,2,4,3,5];console.log (Array,array.sort ());//[1,2,3,4,5] [1,2,3,4,5]

String strings can also be sorted by using call () or apply ()

var str = ' 12435 '; Console.log (str,array.prototype.sort.apply (Str.split (")). Join ("));//' 12435 ' 12345 '

Comparison of methods for arrays and strings in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.