Javascript arrays and common functions

  • 2020-03-30 02:56:22
  • OfStack

1. Know arrays

1.1 define an array

Declare an array of 10 elements:

var a = new Array(10);

At this point, memory space has been allocated for a, containing 10 elements, and is called with the array name and [subscript], for example, a[2] but the element is not initialized, and the call returns undefined.
The following code defines and assigns a mutable array.

var a = new Array();
a[0] = 10;
a[1] = "aaa";
a[2] = 12.6;

As mentioned above, you can put objects in an array, such as the following code:


var a =    new Array();
a[0]    = true;
a[1]    = document.getElementById("text");
a[2]    = {x:11, y:22};
a[3]    = new Array();

Arrays can also be directly assigned when instantiated, for example:


var a = new Array(1, 2, 3, 4, 5);
var b = [1, 2, 3, 4, 5];

A and b are both arrays, except that b USES an implicit declaration to create another instance, where alert(a==b) will pop up false

1.2 multidimensional array


var a = new Array();
a[0] = new Array();
a[0][0] = 1;
alert(a[0][0]);  //Pop up 1

Assign a value when declaring

var a = new Array([1,2,3], [4,5,6],[7,8,9]);
var b = [[1,2,3], [4,5,6], [7,8,9]];

The result is the same: a is instantiated conventionally, b is implicit, and the result is a multidimensional array.

1.3 Array literals

I don't know what it's called in Chinese, a text array?
Speaking of arrays, you have to say Array ; Literals, Array is a special object, the object has a unique attributes and methods, through the object name. Attribute, object. () method to value and calls, and Array is the values by subscripting, Array Literals with Array has a lot in common, is a set of data types, but the Array Literals fundamentally speaking, is an object, the declaration and calls, and there is a difference between an Array:


var aa = new Object();
aa.x = "cat";
aa.y = "sunny";
alert(aa.x);    //Pop up the cat

Create a simple object that is normally called through aa.x, but if you think of it as Array  For literals, alert(aa[" x ") will pop up cat as well


var a = {x:"cat",    y:"sunny"};
alert(a["y"]);  //Pop-up sunny

This is another way to create an object, and the result is the same


2. Operation of array elements

As mentioned above, you can read and write elements from an array [index]
The range of subscripts is 0 (23(superscript 2) -1). When subscripts are negative, floating point, or even Boolean, the array is automatically converted to an object type. For example:


var b    = new Array();
b[2.2]    = "XXXXX";
alert(b[2.2]);  //-> XXXXX

This is equivalent to b[" 2.2 "]  = "XXXXX".

2.1 loop of array


var a = [1,2,3,4,5,6];
for(var i =0; i<a.length; i++){
alert(a[i]);
}

This is the most commonly used, and as you walk through the array, the code will pop up 1 through 6
Another commonly used:

var a = [1,2,3,4,5,6];
for(var e in a){
alert(e);
}

Again, 1 to 6, for... In is the traversal object (array is a special object) object, used on the array, because the array does not have the property name, so the direct output value, this structure statement is used on the object, such as the following:


var a = {x:1,y:2,z:3};
for(var e in a){
alert(e    + ":" + a[e]);
}

At this point, e takes the attribute name, namely x, y, x, and to get the value, it takes the array name [attribute], so a[e] is equal to a[" x "], a[" y "], a[" z "].

2.2 commonly used array functions


concat

Appends an array to an existing array and returns a new array without affecting the existing array:


var a = [123];
var b = "sunnycat";
var c =    ["www",21,"ido"];
var d = {x:3.14, y:"SK"};
var e = [1,2,3,4,[5,6,[7,8]]];

alert(a.concat(b));     // -> 123,sunnycat
alert(a);  //    -> 123
alert(b.concat(c, d));       // -> sunnycatwww,21,ido[object    Object]
alert(c.concat(b));     // -> www,21,ido,sunnycat
alert(e.concat(11,22,33).join(" #    "));       // -> 1 # 2 # 3    # 4 # 5,6,7,8 # 11 # 22 # 33

It's important to note that can only be used for an array or string, if be connected in front of (a) is numeric, Boolean, object, would be an error, the array of strings, the string will follow first element array joining together into a new element, and the connection string array will add new elements (which I don't know why, insiders revealed), for an array containing an array, object, remained intact after the connection.

The join

String the array with the specified spacer:


var a = ['a','b','c','d','e','f','g'];
lert(a.join(","));   //-> A,b,c,d,e,f,g is the same thing as a t string ().
alert(a.join(" x "));  // -> a x b x c x d x e x f x g

This is easy to understand, but it is important to note that only one dimensional arrays are converted. If there are arrays in the array, instead of the string specified by the join, the default toString() is used, for example


var a =    ['a','b','c','d','e','f','g',[11,22,33]];
alert(a.join(" * "));  // -> a * b * c * d * e * f * g *    11,22,33

Note: the array inside the array, and there is no * connection

The pop

Deletes the last element of the array and returns that element


var a =    ["aa","bb","cc"];
document.write(a.pop());    // -> cc
document.write(a);        // -> aa, bb

Note: if the array is empty, return undefined

A push

Adds an array to the end of the array and returns the new length of the array


var a =    ["aa","bb","cc"];
document.write(a.push("dd"));    // -> 4
document.write(a);        // -> aa,bb,cc,dd
document.write(a.push([1,2,3]));  // -> 5
document.write(a);        // -> aa,bb,cc,dd,1,2,3

The difference between concat and concat is that concat does not affect the original array and returns the new array directly, while push directly modifies the original array and returns the new length of the array

sort

Array sort. Let's do an example


var a = [11,2,3,33445,5654,654,"asd","b"];
alert(a.sort()); // -> 11,2,3,33445,5654,654,asd,b

That's not surprising, right, sort is not by integer size, it's by string comparison, it's by ANSI code comparison for the first character, it's by ANSI code comparison for the first character, it's by ANSI code comparison for the first character, it's by ANSI code comparison for the smaller character, it's by ANSI code comparison for the second character for the same thing, if you want to compare by integer value, you can do that


var a = [11,2,3,33445,5654,654];
a.sort(function(a,b) {
return a - b;
});
alert(a);  //    -> 2,3,11,654,5654,33445

Sort () method has an optional argument, which is the function in the code. This is a simple example. You can't sort non-numbers

reverse

I'm going to reverse sort the array just like sort(), and I'm going to take the ASCII value of the first character and compare it


var a = [11,3,5,66,4];
alert(a.reverse());  // -> 4,66,5,3,11

If the array contains an array, it is treated as an object and the elements are not solved


var a = ['a','b','c','d','e','f','g',[4,11,33]];
alert(a.reverse());  // -> 4,11,33,g,f,e,d,c,b,a
alert(a.join(" * "));  // -> 4,11,33 * g * f * e * d * c * b * a

In principle, it should be the last row in row 11, because here, 4,11,33 are compared as a complete object, so it is ranked first
If you don't understand, join() makes it much clearer

The shift

Deletes the first element of the array and returns that element, much like pop


var a =    ["aa","bb","cc"];
document.write(a.shift());   // -> aa
document.write(a);        // -> bb,cc

Note: when the array is empty, undefined is returned

unshift

Instead of shift, add an element to the front of the array and return the new length of the array


var a =    ["aa","bb","cc"];
document.write(a.unshift(11));   //-> Note: return undefined under IE
document.write(a);        // -> 11,aa,bb,cc
document.write(a.unshift([11,22]));   // -> 5
document.write(a);        // -> 11,22,11,aa,bb,cc
document.write(a.unshift("cat"));  // -> 6
document.write(a);        // -> cat,11,22,11,aa,bb,cc

Notice that this method will return undefined under IE, which looks like a Microsoft bug, and I can play with the new array length correctly under firefox

slice

Return array fragment


var a = ['a','b','c','d','e','f','g'];
alert(a.slice(1,2));  // -> b
alert(a.slice(2));    // -> c,d,e,f,g
alert(a.slice(-4));   // -> d,e,f,g
alert(a.slice(-2,-6));    //-> empty

A. soice (1,2), the number between index 1 and index 2. Note that the index 2 is not included
If there is only one argument, default to the end of the array
Minus 4 is the fourth element from the bottom, so it returns the four elements from the bottom
The last line, starting at the second from the bottom, because it intercepts later, it obviously can't fetch the previous element, so it returns an empty array, if I change that to & PI; A.sc (-6,-2) returns b,c,d,e

splice

Deletes the element of a fragment from the array and returns the deleted element


var a = [1,2,3,4,5,6,7,8,9];
document.write(a.splice(3,2));    // -> 4,5
document.write(a);        // -> 1,2,3,6,7,8,9
document.write(a.splice(4));  //-> Note: return empty under IE
document.write(a);        // -> 1,2,3,6
document.write(a.splice(0,1));    // -> 1
document.write(a);        // -> 2,3,6
document.write(a.splice(1,1,["aa","bb","cc"]));   // -> 3
document.write(a);        // -> 2,aa,bb,cc,6,7,8,9
document.write(a.splice(1,2,"ee").join("#")); // -> aa,bb,cc#6
document.write(a);        // -> 2,ee,7,8,9
document.write(a.splice(1,2,"cc","aa","tt").join("#"));  // -> ee#7
document.write(a);        // -> 2,cc,aa,tt,8,9

Note that under IE, the second parameter is required, and if not filled in, the default value is 0, for example, a.scplice (4), and under IE, the result is the same as that of a.scplice (4,0).

The toString

Converts an array to a string, and all objects, not just arrays, can use this method


var a =    [5,6,7,8,9,["A","BB"],100];
document.write(a.toString());    // -> 5,6,7,8,9,A,BB,100
var b = new Date()
document.write(b.toString());    // -> Sat Aug 8 17:08:32 UTC+0800    2009
var c = function(s){
alert(s);
}
document.write(c.toString());    // -> function(s){ alert(s); }

Boolean returns true or false, object returns [object objectname]
In contrast to the join() method, join() replaces only a one-dimensional array, while toString() completely flatlines the entire array (one-dimensional or multidimensional)
At the same time, this method can be used for conversion of hexadecimal, hexadecimal, hexadecimal, hexadecimal, etc. :


var a =    [5,6,7,8,9,"A","BB",100];
for(var i=0; i<a.length; i++){
document.write(a[i].toString()    + "  The binary of  "    + a[i].toString(2) + "  Octal is  " + a[i].toString(8) + "  Hexadecimal is  " + a[i].toString(16));  //    -> 4,5
}

Output results:

5  The binary of  101  Octal is  5  Hexadecimal is  5
6  The binary of  110  Octal is  6  Hexadecimal is  6
7  The binary of  111  Octal is  7  Hexadecimal is  7
8  The binary of  1000  Octal is  10  Hexadecimal is  8
9  The binary of  1001  Octal is  11  Hexadecimal is  9
A  The binary of  A  Octal is  A  Hexadecimal is  A
BB  The binary of  BB  Octal is  BB  Hexadecimal is  BB
100  The binary of  1100100  Octal is  144  Hexadecimal is  64

Conversion can only be done on elements, and if the entire array is converted, the array is returned intact

toLocaleString

Returns a local format string, mainly used on the Date object


var a = new Date();
document.write(a.toString());    // -> Sat Aug 8 17:28:36 UTC+0800    2009
document.write(a.toLocaleString());   //-> August 8, 2009 17:28:36
document.write(a.toLocaleDateString());   //-> August 8, 2009

The difference is that toString() returns the standard format, and toLocaleString() returns the full date in the local format (in the [control panel] > > [region and language options], by modifying the [time] and [long date] formats), toLocaleDateString() is the same as toLocaleString(), but with less time

The valueOf

Returns different primitive values for different objects, similar to toString() for output, but toString() returns a string type and valueOf() returns the original object type


var a = [1,2,3,[4,5,6,[7,8,9]]];
var b = new Date();
var c = true;
var d = function(){
alert("sunnycat");
};
document.write(a.valueOf());    // -> 1,2,3,4,5,6,7,8,9
document.write(typeof (a.valueOf()));  // -> object
document.write(b.valueOf());    // -> 1249874470052
document.write(typeof(b.valueOf()));  // -> number
document.write(c.valueOf());    // -> true
document.write(typeof(c.valueOf()));  // -> boolean
document.write(d.valueOf());    // -> function () {    alert("sunnycat"); }
document.write(typeof(d.valueOf()));  // -> function

Arrays are also objects, so typeof ; (a.valueof ()) returns an object, still a multidimensional array


var a = [1,2,3,[4,5,6,[7,8,9]]];
var aa = a.valueOf();
document.write(aa[3][3][1]); // -> 8


Related articles: