方法
splice()
删除元素,并向数组添加新元素。这个方法很重要。
var books = [
{
id: 1,
name: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
];
//输出books数组
console.log(books);
//删除数组中第二个元素
books.splice(1,1);
//输出删除后的books数组
console.log(books);
//删除元素,并向数组添加元素
books.splice(1,1,{id: 5, name: '《人月神话》', date: '1996-3', price: 250, count: 10});
//输出结果
console.log(books);
结果
shift()
删除并返回数组的第一个元素
var books = [
{
id: 1,
name: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
];
//删除第一个元素,并返回它
console.log(books.shift());
//输出删除元素后的数组
console.log(books);
结果
pop()
删除并返回数组的最后一个元素
var books = [
{
id: 1,
name: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
];
//删除并返回最后一个元素
console.log(books.pop());
//输出删除元素后的数组
console.log(books)