JavaScript中,由于数组长度是可变的,因此可以通过直接定义新的成员而将其添加到数组中:
var o = [2,3,5]; o[3] = 7; console.log(o);//[2,3,5,7]
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]
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]
var p = o.pop(); console.log(p);//17 console.log(o.length);//9
var s = o.shift(); console.log(s);//2013 console.log(o.length);//8
除了shift()语句和pop()语句,还可以通过delete操作符来删除数组中的成员。与shift()和pop()不同的是,delete操作后数组的length属性将保持不变,也即数组将变得不连续。
JavaScript中还可以通过设定数组的length属性来对数组进行修改:当length值小于数组成员数时,JavaScript将对数组进行截取;当length值大于数组成员数时,JavaScript会将数组变得不连续。如果length值只读,那么在数组中直接定义新成员的操作将会失败:
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]