In JavaScript, since the array length is variable, you can add new members to the array by directly defining them:
var o = [2,3,5];
o[3] = 7;
console.log(o);//[2,3,5,7]
In addition to this method, the same purpose can also be achieved by using the push() statement:
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:
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:
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:
var s = o.shift();
console.log(s);//2013
console.log(o.length);//8
In addition to the shift() statement and pop() statement, 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.
You can also modify the array in JavaScript 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 change the array into It's not continuous. If the length value is read-only, then directly defining new members in the array will fail:
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]