One . Transformation method

All objects have toLocaleString(),toString() and valueOf() Method . call toString() Method returns a comma separated string that is concatenated from the strings of each value in the array . And call valueOf() Return or array .

valueOf() Method returns Array The original value of the object .

The original value is from Array All objects derived from objects inherit .

valueOf() The method is usually made up of JavaScript Call automatically in the background , Not explicitly in the code .

Be careful : valueOf() Method does not change the original array .

eg:

 var colors=["red","green","blue"];
alert(colors.toString()); //red","green","blue
alert(colors.valueOf()); //red","green","blue
alert(colors); //red","green","blue
alert(typeof(colors.toString()));//string
alert(typeof(colors.valueOf())); //object
alert(Object.prototype.toString.call(colors.valueOf()));//[object Array]

As can be seen from the above example , Call array toString() Method , Returns the string form of an array , call valueOf() Method returns an array . What needs to be noted here is , because alert() To receive string parameters , So it will call in the background toString() Method , So it gets called directly toString() The same result .

toLocaleString() Method

toLocaleString() Method also creates a comma separated string of array values , And toString() and valueOf() The difference is that it takes the value of each item , Called for each item toLocaleString() Method , instead of toString() Method .

eg:

 var person1={
toLocaleString:function(){
return "toLocale1";
},
toString:function(){
return "toSt1";
}
}
var person2={
toLocaleString:function(){
return "toLocale2";
},
toString:function(){
return "toSt2";
}
}
var person=[person1,person2];
alert(person); //toSt1,toSt2, Because it calls toString Method .
alert(person.toString()); //toSt1,toSt2
alert(person.toLocaleString()); //toLocale1,toLocale2

Array inherited toLocaleString(),toString() and valueOf() Method , By default, array items are returned as comma separated strings . Use join() Method , You can use custom separators to build this string ,join() Method takes only one parameter , That is, the string used as the separator , Then return the string that uses the array item .

eg:

 var colors=["red","green","blue"];
alert(colors.join(",")); //red,green,blue
alert(colors.join("||"));//red||green||blue
alert(colors.join(undefined));//red,green,blu

Be careful :

(1) If not join() Method passes in any value , Or send it undefined, Then use comma as separator .IE7 And earlier versions use strings incorrectly “undefined” As a separator .

(2) If the value of an item in the array is null or undefined, So that's the value join(),toLocaleString(),toString() and valueOf() Method returns an empty string .

Two . Stack method

Is a kind of the stack LIFO(Last-In-First-Out Last in, first out ) Data structure of , That is, the newly added item is removed at the earliest . Insertion of items in stack ( push ) And remove ( eject ), The value occurs at the top of the stack .ECMAScript Provide push() and pop() Method to implement stack like behavior .

1.push(), Add item , Returns the length of the modified array .

2.pop(), Reduce , Return removed items .

eg:

 var colors=new Array();
var count=colors.push("red","green");
alert(count);//
count=colors.push("pink");
alert(count);//
var item=colors.pop();
alert(item);//pink
alert(colors);//red,green

Stack methods can be used with other array methods .

3、 ... and . Queue method

The access rule of queue data structure is FIFO(First-In-First-Out, fifo ). Queues add items at the end of the list , Remove items at the front of the list .

1.push()

2.shift(), Remove the first item in the array , And return the modifier .

eg:

 var colors=new Array();
var count=colors.push("red","green");
alert(count);//
count=colors.push("pink");
alert(count);//
var item=colors.shift();//red
alert(item);//red
alert(colors);//green,pink

3. A queue in the opposite direction , That is, add items to the front of the array , Remove item at the end .

(1)unshift(), add to , Add any item to the front of the array and return the length of the array .

(2)pop()

eg:

 var colors=new Array();
var count=colors.unshift("red","green");
alert(count);//
count=colors.unshift("pink");
alert(count);//
var item=colors.pop();//green
alert(item);//green
alert(colors);//pink,red

Be careful :

IE7 And earlier versions of Javascript There is a deviation in the implementation of , Its unshift() Method always returns undefined Instead of the new length of the array ,IE8 In incompatible mode, the correct length value is returned .

Four . Reorder method

1.reverse() Method : Reverse the order of array items .

eg:

 var values=[1,2,3,4,5];
values.reverse();
alert(values);//5,4,3,2,1

2.sort() Method : Array items in ascending order , That is, the smallest value is in the front , The largest value is at the end , But here's the thing :sort() Method will call the toString() Method transformation method , Then compare the resulting string , To determine how to sort . Even if every item in the array is a number ,sort() Method also compares strings .

eg:

 var values=[1,2,3,4,5,10,11];
values.sort();
alert(values);//1,10,11,2,3,4,5

explain (W3C)

If the method is called without parameters , The elements in the array will be sorted alphabetically , To be more precise , It's in the order of character encoding . To achieve this , First of all, the elements of the array should be converted into strings ( If necessary, ), For comparison .

If you want to sort by other criteria , You need to provide a comparison function , This function compares two values , Then return a number that describes the relative order of the two values . The comparison function should have two arguments a and b, Its return value is as follows :

  • if a Less than b, In the sorted array a It should appear in b Before , Return a value less than 0 Value .
  • if a be equal to b, Then return to 0.
  • if a Greater than b, Return a value greater than 0 Value .

eg:

 function compare(value1,value2){
if(value1<value2){
return -1;
}else if(value1>value2){
return 1;
}else{
return 0;
}
}
var values=[1,2,3,4,5,10,11];
values.sort(compare);
alert(values);//1,2,3,4,5,10,11

You can also change the return value of the comparison function , To achieve the effect of descending order :

eg:

 function compare(value1,value2){
if(value1<value2){
return 1;
}else if(value1>value2){
return -1;
}else{
return 0;
}
}
var values=[1,2,3,4,5,10,11];
values.sort(compare);
alert(values);//11,10,5,4,3,2,1

Be careful :

(1) Of course , If you simply want to reverse the original order , Regardless of ascending or descending order , Use reserve() Faster .

(2)reverse() and sort() The return value of the method is the sorted array .

(3) For numeric types or valueOf() Method returns an object model of numeric type , You can use the following functions :

 function compare(value1.value2){
return value2-value1;
}

Because the comparison function returns a value less than 0, be equal to 0 Or greater than 0 To affect the sorting result , So subtraction can handle these situations properly .

JS Altitude 5. Reference type (4)Array Types of various methods of more related articles

  1. JS_ Altitude 5. Reference type (4)Array Types of methods

    One . Transformation method All objects have toLocaleString(),toString() and valueOf() Method . call toString() Method returns a comma separated string that is concatenated from the strings of each value in the array ...

  2. JS Altitude 5. Reference type (3)Array type - Detect arrays

    1. instanceof The operator (ECMAScript3) For a web page , Or a global scope , Use instanceof Operator to detect the array can get satisfactory results . grammar :if(value instan ...

  3. JS Altitude 5. Reference type (2)Array type

    Array type : ECMAScript Each item of the array can hold any type of data , The size of the array can be adjusted dynamically . The basic way to create arrays : (1) Use Array Constructors var color=new Array(); ...

  4. Js Take notes -&gt; Reference type

    1 . Object object    2 . Array object :        test method :ES5 : isArray        Transformation method : toLocaleString , toString , val ...

  5. 《JS Altitude 》 Reference type learning notes

    2 The full moon is over , Before the end is Nirvana like a Phoenix . While working , While engaged in scientific research busy, a bit breathless , My heart can't help being impetuous . however , No matter what , Just be patient . Concentrate on doing , It's always going to be good , Mentality is really important .Anyway ...

  6. JavaScript Of reference types Array Type 1

    One . brief introduction except Object outside ,Array I'm afraid the type is ECMAScript The most commonly used type in . Let's analyze ECMAScript The similarities and differences between arrays in and arrays in other languages : 1. The same thing : (1) They're all data sequences ...

  7. JavaScript Of reference types Array type API Detailed explanation

    Array The type is also ECMASCRIPT The most common data type in , And each item of data can hold any type of value , And the size of the array can be adjusted dynamically , Can grow automatically as data is added to accommodate new data . below , Some common ways to summarize data ...

  8. Of reference types Array type

    Array type ECMAScript Arrays are the same as arrays in other languages , It's all an ordered list of data . however ECMAScript Each item of the array can hold any type of data . and ,ECMAScript Arrays can be dynamically adjusted . 1. Create and ...

  9. JavaScript Reference type of (Array type )

    except Object type ,Array yes ECMAScript The most commonly used type in . Different from other languages ,ECMAScript Each item of the array can hold any type of data . and ,ECMAScript The size of the array can be adjusted dynamically ...

Random recommendation

  1. CCNA Network engineer learning process (3) General network design model and basic network protocol

        This section introduces the layered network design model and basic network protocols , Include ARP agreement ,ICMP The protocol and IP agreement .     (1) Three layer network architecture : A good campus network design should be a layered design . It is generally divided into access layer . Convergence layer ( The distribution layer ). nucleus ...

  2. AngularJs Preliminary study notes (part1)

    One . Abstract : angular Is to use JavaScript The front end of writing mvc frame , Help developers write modern single page applications . It's especially suitable for writing lots of CRUD Operation of the , have Ajax Style client applications . Two . summary : Angula ...

  3. C In language fread and fwrite

    C In language fread and fwrite It's a way to manipulate files . 1. fread Responsible for reading the contents of the file from the open file pointer . The function prototype :size_t fread(void *p, size_t size, si ...

  4. Maven-- Lifecycles and plug-ins ( Four )

    <Maven-- Build development environment ( One )> <Maven-- Build enterprise warehouse ( Two )> <Maven— A few questions that need to be added ( 3、 ... and )> <Maven— Lifecycles and plug-ins ( Four )&g ...

  5. iptables Practical tutorial ( One ): Basic concepts and principles

    summary iptables yes linux Bring your own firewall software , Used for configuration IPv4 Packet filtering or NAT(IPv6 use ip6tables). stay linux On , The firewall is actually a part of the system kernel , be based on Netfilter The architecture , basic ...

  6. .Neter Get along well with Linux The second series :Linux File directory and file directory permissions

    One .Linux File directory under brief introduction :linux The file system of is a hierarchical tree structure , Here it is At the top of the structure is the root directory “/”, Then create... In this directory Other directories . A deep understanding linux The file directory is very important , As shown below ...

  7. Reptiles ——BeautifulSoup and Xpath

    Reptiles can be divided into three parts : Crawling ——> analysis ——> Storage One Beautiful Soup: Beautiful Soup Provide some simple .python Function to handle navigation . Search for . Modify the analysis tree ...

  8. Prototype pattern of design pattern (c++)

    Problem description See this pattern , It's easy to think of what I saw when I was a child < Journey to the west >, The monkey king, the great sage of Qi Tian, can pass the 3 Root hair immediately reproduced thousands of Monkey King , It works against goblins ( Quantity is the most important ). Prototy ...

  9. js The simplest way to get all dates between two dates

    Date.prototype.format = function() { var s = ''; var mouth = (this.getMonth() + 1)>=10?(this.getM ...

  10. ThreadingTCPServer How to set port reuse

    A typical TCPServer The establishment of the #ThreadingTCPServer from ThreadingMixIn and TCPServer Inherit #class ThreadingTCPServer(Threading ...