Ways to compare arrays and strings in JavaScript _javascript tips

Source: Internet
Author: User
Tags numeric numeric value

Front.

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

can be indexed

ECMAScript5 defines a method of accessing characters by using square brackets plus a numeric index to access specific characters in the 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, the string behaves like an array of facts so that a common array method can be applied to a string

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[));/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[));/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 strings based on the specified delimiter and places the result in an array, which can be either a string or a regular expression

The method can accept (optionally) the second parameter to specify the size of the array. If the second parameter is a value in the 0-array.length range, the output is in the specified parameter, and the other case outputs all the results

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 (/[^\,]+/));//will remove the string other than the comma into the separator character [", ",", ",", ",", ",", "," ",", "," ",", ",", ",", ",",

"Join ()"

The join () method can use a different delimiter to build this string, the join () method receives only one argument, serves as a string for the delimiter, and then returns a string containing all the array items

If you do not pass in any values to the join () method, use a comma as the delimiter

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 (a);
B.join ('-');//'---------', a string of 9 hyphen characters

If the value of an item in an array is null or undefined, the value is represented in 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 together with a concatenation 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 Create Method slice (), which is used to create substrings and child arrays, respectively

The slice () method creates a new array (or string) based on one or more items in the current array (or string), accepting one or two arguments, that is, to return the starting and ending positions of the items, and finally to return the new array (or string)

The slice (Start,end) method requires two parameters, start and end, to return a child array (or string) from the start position to (but not include) a last position in the array (or string), or if it is undefined or not, Returns all items from the start position to the end of the array (or string)

If start is a negative number, then 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);//'
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

Both the string and the array have two methods for finding locations: IndexOf () and LastIndexOf (). The position method and the bracket [] reading method are exactly the opposite, one is to find the index by item, one is to find the item through the index

"IndexOf ()"

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

The search parameter in the string invokes the string () transformation function to convert the parameter's non string value to a string, while the search parameter in the array is compared using the strict equality operator (= = =)

Either an array or a string, the second argument start implicitly invokes the number () transformation function to convert the start Non-numeric value (except undefined) to a numeric value, or the start = 0 if the argument is omitted or the parameter is undefined, Nan.

If the start argument is a negative number, the processing of the string is start=0 and the array is processed as Start = max (0,start+length)

var string = ' Hello World ';
Console.log (String.IndexOf (' ld '));//9
Console.log (string.indexof (' ld ', undefined));//9
Console.log ( String.IndexOf (' ld ', NaN));//9
Console.log (string.indexof (' ld ', -1);//9 console.log (
' ld ' ));//15 Console.log (
string.indexof (' ld ', [ten]));//15 Console.log (
' true ', [10]); String.IndexOf
Console.log (String.IndexOf (false,[10));//-1
var arr = [' A ', ' B ', ' C ', ' d ', ' e ', ' A ', ' B '];
Console.log (Arr.indexof (' a ', undefined));//0
Console.log (Arr.indexof (' A ', NaN));//0
Console.log ( Arr.indexof (' A ', 1));//5
Console.log (Arr.indexof (' A ', true))//5
console.log (Arr.indexof (' A ', -1));//max ( 0,-1+7) = 6; -1
Console.log (Arr.indexof (' A ', -5));//max (0,-5+7) =2; 5
console.log (Arr.indexof (' A ', -50));//max (0,-50+7) = 0; 0

"LastIndexOf ()"

In contrast to the indexof () method, the LastIndexOf () method looks from right to left

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

Similarly, the search parameter in the string calls the string () transformation function to convert the parameter's non string value to a string, while the search parameter in the array is compared using the strict equality operator (= = =)

Either an array or a string, the second argument start implicitly invokes the number () transformation function to convert the start Non-numeric value (except undefined) to a numeric value

If this argument is omitted or if 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 argument is a negative number, the processing of the string is start=0 and the array is processed as Start = max (0,start+length)

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

var arr = [' A ', ' B ', ' C ', ' d ', ' e ', ' A ', ' B '];
Console.log (Arr.lastindexof (' B '));//6
Console.log (arr.lastindexof (' B ', undefined));//-1
Console.log ( Arr.lastindexof (' A ', undefined));//0
Console.log (arr.lastindexof (' B ', NaN));//-1
Console.log ( Arr.lastindexof (' B ', 1));//1
Console.log (arr.lastindexof (' B ', -1));//max (0,-1+7) =6; 6
Console.log ( Arr.lastindexof (' B ', -5));//max (0,-5+7) = 2; 1
console.log (arr.lastindexof (' B ', -50));//max (0,-50+7) = 0;-1

The above JavaScript in the array and string method comparison is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

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.