js array common operations and a detailed example of array and string conversion

  • 2020-10-23 20:01:09
  • OfStack

This article describes the js array common operations and array and string conversion method. To share for your reference, the details are as follows:

Array and string conversion


<script type="text/javascript">
var obj="new1abcdefg".replace(/(.)(?=[^$])/g,"$1,").split(",");
// Strings are converted to arrays 
var obj2 = "new2abcdefg".split("");  // Strings are converted to arrays 
alert(obj);
alert(obj.length);
alert(obj instanceof Array);
alert(obj.join("")); // The array is converted to a string 
</script>

Common operations for js arrays

1. Creation of arrays


var arrayObj = new Array(); // create 1 An array 
var arrayObj = new Array([size]); // create 1 Number of arrays and specify length, not upper bound, but length 
var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); create 1 An array and an assignment 

To be clear, although the second method specifies the length of the array, in all cases the array is variable in length, which means that even if the length is specified as 5, you can still store elements outside the specified length. Note that the length changes accordingly.

2, access to the elements of the array


var testGetArrValue=arrayObj[1]; // Gets the element value of the array 
arrayObj[1]= " This is the new value "; // Assign a new value to an array element 

3. Add array elements


arrayObj. push([item1 [item2 [. . . [itemN ]]]]);//  will 1 Two or more new elements are added to the end of the array and the new length of the array is returned 
arrayObj.unshift([item1 [item2 [. . . [itemN ]]]]);//  will 1 When one or more new elements are added to the beginning of an array, the elements in the array automatically move back, returning the new length of the array 
arrayObj.splice(insertPos,0,[item1[, item2[, . . . [,itemN]]]]);// will 1 Two or more new elements are inserted into the array at the specified location. The element inserted at the specified location is automatically moved back and returned "" . 

4, the deletion of array elements


arrayObj.pop(); // Remove the last 1 Returns the value of the element 
arrayObj.shift(); // Remove the former 1 Returns the value of the element, and the elements in the array automatically move forward 
arrayObj.splice(deletePos,deleteCount); // Deletes from the specified location deletePos The specified number to start with deleteCount Returns the removed element as an array 

5. Interception and merger of arrays


arrayObj.slice(start, [end]); // Returns an array as an array 1 Partial, note not included  end  The corresponding element, if omitted  end  Will be copied 
start  All of the elements after that 
arrayObj.concat([item1[, item2[, . . . [,itemN]]]]); // Concatenates multiple arrays (which can also be strings, or a mixture of arrays and strings) as 1 Returns a new array that has been concatenated 

6. Copy of array


arrayObj.slice(0); // Returns a copy of the array 1 A new array, not a point 
arrayObj.concat(); // Returns a copy of the array 1 A new array, not a point 

7. Sorting array elements


arrayObj.reverse(); // Reverses the elements (first to last, last to first) to return the array address 
arrayObj.sort(); // Sorts array elements and returns array addresses 

8. Stringing array elements

arrayObj.join(separator); // Returns a string that concatenates the values of each element of the array at 1, separated by separator.

toLocaleString, toString, valueOf: can be regarded as a special use of join, not commonly used

2. Three properties of an array object

1. length attribute

The Length attribute represents the length of the array, that is, the number of elements in it. Because the index of an array always starts at 0, the upper and lower limits of an array are 0 and ES53en-1. Unlike most other languages, the length attribute of the JavaScript array is mutable, which requires special attention. When the length attribute is set larger, the state of the entire array does not actually change, only the length attribute becomes larger. When the length attribute is set smaller than the original, the values of elements in the original array with indexes greater than or equal to length are all lost. Here is an example of changing the length attribute:


var arr=[12,23,5,3,25,98,76,54,56,76];
// Defines the 1 containing 10 An array of Numbers 
alert(arr.length); // Displays the length of the array 10
arr.length=12; // Increase the length of the array 
alert(arr.length); // Displays that the length of the array has changed 12
alert(arr[8]); // According to the first 9 The value of the elements, is 56
arr.length=5; // Reduce the length of the array to 5 Index equals or exceeds 5 Elements are discarded 
alert(arr[8]); // According to the first 9 The number of elements has changed "undefined"
arr.length=10; // Restore the array length to 10
alert(arr[8]); // Although the length is restored to 10 But the first 9 Three elements can not be recalled, display "undefined"

From the above code we can clearly see the nature of the length attribute. But not only can the length object be set explicitly, it can also be modified implicitly.

You can use an undeclared variable in JavaScript, or you can use an undefined array element with an index greater than or equal to length, in which case the value of the length attribute is set to the value of the element index used plus 1. For example, the following code:


var arr=[12,23,5,3,25,98,76,54,56,76];
alert(arr.length);
arr[15]=34;
alert(arr.length);

The code also defines an array of 10 Numbers, which is 10 in length as shown by the alert statement. Then I use the element with an index of 15 and assign it a value of 15, that is, arr[15]=34. Then I output the length of the array with the alert statement, and I get 16. However, this is a very surprising feature for developers used to strongly typed programming. In fact, the initial length of an array created in the form of new Array() is zero, and it is the manipulation of undefined elements in the array that changes the length of the array.

As you can see from the above introduction, the length attribute is so magical that you can easily increase or decrease the size of an array by using it. Therefore, a deep understanding of the length attribute is conducive to flexible application in the development process.

2. prototype attribute

Returns a reference to the object type stereotype. The prototype attribute is common to object.

objectName.prototype

The objectName parameter is the name of the object object.

Description: Provides a basic set of functions for the class of the object with the prototype attribute. A new instance of an object "inherits" the operation given to the object prototype.

For array objects, the following example illustrates the purpose of the prototype attribute.

Adds a method to an array object that returns the maximum element value in the array. To do this, declare a function, add it to ES105en.prototype, and use it.


var arrayObj = new Array(); // create 1 An array 
var arrayObj = new Array([size]); // create 1 Number of arrays and specify length, not upper bound, but length 
var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); create 1 An array and an assignment 

0

After this code is executed, y holds the maximum value in the array x, or 6.

3. constructor attribute

Represents the function that creates the object.

object. constructor //object is the name of the object or function.

Note: The constructor attribute is a member of all objects that have prototype. They include all JScript native objects except Global and Math objects. The constructor attribute holds a reference to the function that constructed the specific object instance.

Such as:


x = new String("Hi");
if (x.constructor == String) //  To process (the condition is true). 

or


function MyFunc {
//  The body of the function. 
}
y = new MyFunc;
if (y.constructor == MyFunc) //  To process (the condition is true). 

For arrays:

y = new Array();

Specific use:

Use an array

Basic operation


var arrayObj = new Array(); // create 1 An array 
var arrayObj = new Array([size]); // create 1 Number of arrays and specify length, not upper bound, but length 
var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); create 1 An array and an assignment 

3

Array assignment

You can assign values in sequence as simple as above, or as follows:


var arrayObj = new Array(); // create 1 An array 
var arrayObj = new Array([size]); // create 1 Number of arrays and specify length, not upper bound, but length 
var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); create 1 An array and an assignment 

4

You can also assign values directly to multidimensional arrays


var arrayObj = new Array(); // create 1 An array 
var arrayObj = new Array([size]); // create 1 Number of arrays and specify length, not upper bound, but length 
var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); create 1 An array and an assignment 

5

push: Data can be appended to the last element


var arrayObj = new Array(); // create 1 An array 
var arrayObj = new Array([size]); // create 1 Number of arrays and specify length, not upper bound, but length 
var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); create 1 An array and an assignment 

6

pop: Pop the last element, last in, first out


var arr=new Array();
 var s;
 arr[0]="a1";
 arr[1]="a2";
 arr[2]="a3";
 arr[3]="a4";
 s=arr.pop();// Pop up the last 1 An element , The value to pay s, And delete the last 1 An element 
 alert(s);
 for(i=0;i<arr.length;i++)
 {
 document.writeln(arr[i]);
 }
 // According to : a1 a2 a3

unshift: Insert before the first,


 var arr=new Array();
 var s;
 arr[0]="a1";
 arr[1]="a2";
 arr[2]="a3";
 arr[3]="a4";
 arr.unshift(" The first 1"," The first 2");// In the first 1 Before the element , The whole of the back moves back 
 for(i=0;i<arr.length;i++)
 {
 document.write(arr[i]+":");
 }
 // According to :  The first 1: The first 2:a1:a2:a3:a4:

shift: Pop the first element, first in, first out


var arrayObj = new Array(); // create 1 An array 
var arrayObj = new Array([size]); // create 1 Number of arrays and specify length, not upper bound, but length 
var arrayObj = new Array([element0[, element1[, ...[, elementN]]]]); create 1 An array and an assignment 

9

join: Concatenates all the contents of the array using the join method of the array

join(string val) of the array can connect the array elements and insert val in the middle. When the content of the drop-down box is displayed interactively on the web page, the content can be loaded into the array, and then the content can be displayed in innerHTML


<script>
  var a=new Array("cctv","sxtv","tytv");
  var a=new Array(3);
  var a=new Array();
  a[0]="cctv";
  a[1]="sxtv";
  a[2]="tytv";
  a[3]="xzy";
  document.writeln(a.join('<br>'));// If you use it directly a.join(), Will be used by default , segmentation 
</script>

Display:

cctv
sxtv
tytv
xzy

Concatenating strings in this way is much faster than s=s+ "ddd"

sort: Array sort (from small to large)


var arr=new Array(1000)
arr[0]="xbc1";
arr[1]="bcx2";
arr[2]="cctv3";
arr[5]="xctv4";
arr.sort();
for(i=0;i<arr.length;i++)
{
 if(arr[i]!=null)
 document.writeln(arr[i]);
}

reverse: Reverse array, and sort in conjunction with the implementation of large to small sorting


 var arr=new Array()
 arr[0]="a1";
 arr[1]="a2";
 arr[2]="a3";
 arr[3]="a4";
 arr.push(" XingZhiYun ");
 arr.push("0123");
 //arr.sort();
 arr.reverse();// Reverse array arrangement 
 for(i=0;i<arr.length;i++)
 {
 document.writeln(arr[i]);
 }
 // According to : 0123  XingZhiYun  a4 a3 a2 a1

slice: Truncated array assigned to another array (without changing the original array)


var xzy1=new Array();
xzy1=["a","b","c","hello","usa","eng"];
//   0  1  2   3   4   5
var xzy2=xzy1.slice(2,4);// From an array xzy1 the 2 The number element starts here 4 The stop value of the number element ends up being converted to 1 An array 
for(var i=0;i<xzy2.length;i++)
{
 document.write(xzy2[i]+":");// According to c hello
}

Or you could write it this way


<script>
var xzy1=new Array();
xzy1=["a","b","c","hello","usa","eng"];
//   0  1  2   3   4   5
var xzy2=Array.prototype.slice.call(xzy1,2,4);// From an array xzy1 the 2 The number element starts here 4 The stop value of the number element ends up being converted to 1 An array 
for(var i=0;i<xzy2.length;i++)
{
 alert(xzy2[i]);// According to c hello
}
</script>

splice: Array truncated or emptied (changing the original array)


 var arr=new Array();
 var s;
 arr[0]="a1";
 arr[1]="a2";
 arr[2]="a3";
 arr[3]="a4";
 arr[4]="a5";
 arr[5]="a6";
 var arr2=arr.splice(3,2,"x1","x2");// from 3 The start of the number 2 An element , with x1 and x2 replace , And reassign the replacement value to the array arr2
 // If there are no parameters "x1","x2", The corresponding 2 The elements are going to go from arr Remove the , The back push forward 
 for(i=0;i<arr.length;i++)
 {
 document.write(arr[i]+":");// According to : a1:a2:a3:x1:x2:a6:
 }
 document.write("<br/>");
 for(i=0;i<arr2.length;i++)
 {
 document.write(arr2[i]+":");// According to : a4:a5:
 }

Use splice to empty the array


 var arr=new Array();
 arr[0]="a1";
 arr[1]="a2";
 arr[2]="a3";
 arr[3]="a4";
 arr[4]="a5";
 arr[5]="a6";
 alert(arr.length);// According to 6
 arr.splice(0,100000000);// You can think of it as arr Array to empty , We're back to where we started 
 alert(arr.length);// According to 0

concat: Array join


 var arr=new Array();
 var s;
 arr[0]="a1";
 arr[1]="a2";
 arr[2]="a3";
 arr[3]="a4";
 arr[4]="a5";
 arr[5]="a6";
 var arr2=["b1","b2","b3"];
 var arr3=arr.concat(arr2);
 for(i=0;i<arr3.length;i++)
 {
 document.write(arr3[i]+":");// According to : a1:a2:a3:a4:a5:a6:b1:b2:b3:
 }

Using Map

map1:


<script>
var map = {};
map[" zhang 3"] = "1362348754";
map[" li 4"] = "0351-98476345";
map[" The king 5"] = "0358-4873622";
alert(map[" li 4"]);
</script>

Use map={} to empty map;

map2:


<script>
var map = new Array();
map[" zhang 3"] = "1362348754";
map[" li 4"] = "0351-98476345";
map[" The king 5"] = "0358-4873622";
alert(map[" li 4"]);// According to :0351-98476345
alert(map.length);// Here, map.length Is shown as 0
map[0] = "0358-4873622";
map[1] = "0358-4873622";
map[2] = "0358-4873622";
alert(map.length);// Here, map.length Is shown as 3
for(var i=0;i<map.length;i++)
{
 document.write(map[i]);
}
alert(map[" li 4"]);// According to :0351-98476345
</script>

map3:


var map={" The name ":" XingZhiYun "," gender ":" male "," age ":34}
map. Marital status =" married ";// You can add it dynamically 
eval("map. nationality =' The Chinese '");// but map. Subsequent identifiers can only begin with a character , And you can't have - Therefore, the global identifier should not be used here 
alert(map. nationality );
//alert(map. The name );// XingZhiYun 
//alert(map. age );//34
map[" national "]=" The han nationality ";// Or it could be like a control 1 That assignment in the bar , But this one can use any string as a bond , Such as : map["1-2"]=" The han nationality ";alert(map. The name 
+":"+map["1-2"]);// It also displays normally 
alert(map. The name +":"+map. national );
for(var colname in map)
{
 alert(colname );// The name   gender   age   Marital status 
}
for(var colname in map)
{
 alert(map[colname]);// XingZhiYun   male  34  married 
}

You could do that


var s="' The name ':' XingZhiYun ',' gender ':' male ',35:' age '";
eval("var map={"+s+"}");
alert(map[" The name "]);

or


var s=" The name :' XingZhiYun ', gender :' male ',35:' age '";
eval("var map={"+s+"}");
alert(map[" The name "]);

It can also be nested


var map={" personnel ":{" zhang 3":" male "," zhao 6":" female "},
" vehicle ":{" santana ":"6 wan "," buick ":"10 wan "},
" age ":34}
alert(map. personnel . zhao 6);// female 
alert(map. vehicle . santana );//6 wan 

An array that USES custom properties


var a=new Array();
a[0]={};
a[0]. The name =" XingZhiYun ";
a[0]. age =32;
a[1]={};
a[1]. The name =" li 4";
a[1]. age =28;
for(var i=0;i<a.length;i++)
{
 alert(a[i]. The name +":"+a[i]. age );
}

I hope this article has been helpful for JavaScript programming.


Related articles: