pythonslice_shift_push、pop、shift、unshift、slice、splice之数组操作

1.[代码][JavaScript]代码

var a = [1, 2, 3, 4]

// shift,移除数组头部元素并返回

a.shift(); // 1

console.log(a); // [2, 3, 4]

// unshift,在头部插入元素,如果不传参数则不会增加元素,返回操作结束后数组中元素的个数

a.unshift(1); // 4

console.log(a); // [1, 2, 3, 4]

a.unshift(-1, 0); // 6

console.log(a); // [-1, 0, 1, 2, 3, 4]

// slice,切片操作,类似于Python的切片

b = a.slice(); // 浅拷贝,a不变,b变为[-1,0,1,2,3,4]

b = a.slice(1); // 一个参数,从索引为1位置的元素开始切片,b变为[0,1,2,3,4]

b = a.slice(1, 3); // 传入区间,进行切片。切取得到的元素数目为3-1=2,b变为[0,1]

b = a.slice(-1); // 从后往前切片一个元素,b变为[4]

b = a.slice(-2); // 从后往前切片二个元素,b变为[3, 4]

// splice:删除数组中指定区间的元素,还可以添加新元素,相当于替换

// 返回的是删除的元素的数组

// splice(start, [[end][, newElem1][, new Elem2]...])

var array = [1, 2, 3, 4];

array.splice(0); // [1, 2, 3, 4]

console.log(array); // []

array.unshift(1, 2, 3, 4, 5); // 5

console.log(array); // [1, 2, 3, 4, 5]

array.splice(0, 2); // [1, 2]

console.log(array); // [3, 4, 5]

array.splice(0, 1, 6]; // [3]

console.log(array); // [6, 4, 5]

// 而delete删除数组元素却表现怪异

var c = [1, 2, 3];

delete c[0]; // true

console.log(c); // [undefined, 2, 3]

//-----------------------------------------------------------------//

// 这里额外提下splice使用的灵活

// 使用splice可以实现数组元素的删除、插入和替换(即删除并插入)

// A. 删除元素,指定两个参数,第一个参数为要删除的元素的起始位置,第二个参数为要删除的元素的个数

var a = [1, 2, 3, 4, 5];

a.splice(0, 2); // 删除index为0开始的2个元素,即删除1、2,

console.log(a); // a现在为[3, 4, 5]

// B. 插入元素,第一个参数为要删除的元素的起始位置,第二个参数为0,第三个参数、第四个参数...为要插入的元素

var a = [1, 2, 3, 4, 5];

a.splice(2, 0, 6, 7); // 在index为2处插入元素6、7

console.log(a); // a现在为[1, 2, 6, 7, 3, 4, 5]

// C. 替换元素,第一个参数为要删除的元素的起始位置,第二个参数为要删除的元素的个数,第三个参数、第四个参数...为要替换的元素

var a = [1, 2, 3, 4, 5];

a.splice(2, 2, 6, 7); // 用6、7替换index为2开始的2个元素

console.log(a); // a现在为[1, 2, 6, 7, 5]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值