In JavaScript, since the array length is mutable, it can be added to the array by directly defining new members:
The code copy is as follows:
var o = [2,3,5];
o[3] = 7;
console.log(o);//[2,3,5,7]
In addition to this method, the same purpose can be achieved by using the push() statement:
The code copy 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]
If you need to add a new member at the beginning of the array, you can use the unshift() statement:
The code copy is as follows:
o.unshift(2014);
console.log(o);//[2014,2,3,5,7,11,13,17]
o.unshift(2013, 2012);
console.log(o);//[2013,2012,2014, 2,3,5,7,11,13,17]
Corresponding to push(), if you need to delete a member from the end of the array, you can use the pop() statement. The pop() statement will return the deleted member, and the array length will be reduced by 1:
The code copy is as follows:
var p = o.pop();
console.log(p);//17
console.log(o.length);//9
Corresponding to unshift(), if you need to delete a member from the beginning of the array, you can use the shift() statement. The shift() statement will return the deleted member, and the array length will be reduced by 1:
The code copy is as follows:
var s = o.shift();
console.log(s);//2013
console.log(o.length);//8
In addition to shift() statements and pop() statements, you can also delete members in the array through the delete operator. Unlike shift() and pop(), the length property of the array will remain unchanged after the delete operation, that is, the array will become discontinuous.
JavaScript can also modify the array by setting the length attribute of the array: when the length value is less than the number of array members, JavaScript will intercept the array; when the length value is greater than the number of array members, JavaScript will make the array discontinuous. If the length value is read-only, the operation of directly defining new members in the array will fail:
The code copy is as follows:
console.log(o);//[2012,2014, 2,3,5,7,11,13]
o.length = 2;
console.log(o);//[2012,2014]
o.length = 4;
console.log(o);//[2012,2014,undefined,undefined]
var a = [1,2,3];
Object.defineProperty(a, "length", {writable:false});
a[3] = 4;
console.log(a);//[1,2,3]