This article mainly introduces how to add and delete members in JavaScript. This article mainly describes the applications of functions such as push (), unshift (), pop (), and shift, for more information, see JavaScript. Since the array length is variable, you can add a new member to the array by defining it directly:
The Code is as follows:
Var o = [2, 3, 5];
O [3] = 7;
Console. log (o); // [2, 3, 5, 7]
In addition to this method, you can use the push () statement to achieve the same purpose:
The Code is as follows:
O. push (11 );
Console. log (o); // [2, 3, 5, 7, 11]
O. push (13, 17 );
Console. log (o); // [2, 3, 5, 7, 11, 13, 17]
To add a new member at the beginning of the array, you can use the unshift () Statement:
The Code is as follows:
O. unshift (2014 );
Console. log (o); // [,]
O. unshift (2013,201 2 );
Console. log (o); // [2014, 17]
Corresponds to push (). If you want to delete a member from the end of the array, you can use the pop () statement. The pop () Statement returns the deleted member, the array length will be reduced by 1:
The Code is as follows:
Var p = o. pop ();
Console. log (p); // 17
Console. log (o. length); // 9
Corresponds to unshift (). To delete a member from the beginning of the array, you can use the shift () statement. The shift () Statement returns the deleted member, the array length will be reduced by 1:
The Code is as follows:
Var s = o. shift ();
Console. log (s); // 2013
Console. log (o. length); // 8
In addition to the shift () and pop () statements, you can also use the delete operator to delete members in the array. Unlike shift () and pop (), after the delete operation, the length attribute of the array remains unchanged, that is, the array will become discontinuous.
In JavaScript, you can also modify the array by setting the length attribute of the array: when the length value is smaller than the number of array members, JavaScript will intercept the array; when the length value is greater than the number of elements in the array, JavaScript will make the array discontinuous. If the length value is read-only, defining new members in the array will fail:
The Code is as follows:
Console. log (o); // [,]
O. length = 2;
Console. log (o); // [nginx2014]
O. length = 4;
Console. log (o); // [maid, undefined, undefined]
Var a = [1, 2, 3];
Object. defineProperty (a, "length", {writable: false });
A [3] = 4;
Console. log (a); // [1, 2, 3]