数组方法slice和splice

slice(start , end)截取数组

1.方法介绍:不改变原数组,返回截取出来的数组
2.参数两个从哪里开始到哪里结束,第一个参数(必选),可以是负数,代表从右边开始截取,第二个参数,代表到哪里结束,可以是负数,代表从右边查的索引位置。

 // 字面量声明的方式,返回的是字符串 
var names=["George","John","Thomas"];
console.log(names.slice(1,3)); // eo
console.log(names); // George,John,Thomas
// new方式声明的数组,返回的是数组
var arr = new Array(3);
arr[0] = "George";
arr[1] = "John";
arr[2] = "Thomas";
console.log(arr.slice(1,3)); // 输出为["John", "Thomas"]
console.log(arr);  // ["George", "John", "Thomas"]
splice 方法向/从数组中添加/删除项目

1.方法介绍:会改变原数组,返回操作后的数组
2.参数arrayObject.splice(index,howmany,item1,.....,itemX)

index:从什么位置开始,正负整数都可以(必须)
howmany:删除的个数,0代表不删除(W3C必须,测试不传参数代表到最后一位)
item:代表向数组中添加的元素
// 删除元素
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
console.log(arr.splice(1)); // 输出为["John", "Thomas"]
console.log(arr); // 输出为["George"]
// 添加元素
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
console.log(arr.splice(1,0,"bonly")); // 输出为空数组[]
console.log(arr); // 输出为["George", "bonly", "John", "Thomas"]

转载于:https://www.cnblogs.com/bonly-ge/p/9435656.html

JavaScript中的数组有两个常用的方法slicesplice。 1. slice 方法slice 方法是用于从数组中提取指定范围的元素,然后返回一个新的数组。它接受两个参数,即开始索引和结束索引(不包括结束索引本身),如果省略结束索引,则会一直提取到数组末尾。原始数组不会被修改。 示例: ```javascript const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']; const slicedFruits = fruits.slice(1, 4); // 从索引 1 到 4(不包括 4)提取元素 console.log(slicedFruits); // 输出:['banana', 'orange', 'grape'] const slicedFruits2 = fruits.slice(2); // 从索引 2 开始提取元素到数组末尾 console.log(slicedFruits2); // 输出:['orange', 'grape', 'kiwi'] console.log(fruits); // 输出原始数组,不受 slice 方法影响:['apple', 'banana', 'orange', 'grape', 'kiwi'] ``` 2. splice 方法splice 方法用于修改原始数组,它可以用于删除、插入或替换数组中的元素。它接受三个或更多参数,第一个参数是开始索引,第二个参数是需要删除的元素个数,之后的参数是要插入到数组的新元素(可选)。splice 方法会返回一个包含被删除元素的数组。 示例: ```javascript const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']; const deletedFruits = fruits.splice(2, 2); // 从索引 2 开始删除 2 个元素 console.log(deletedFruits); // 输出:['orange', 'grape'] console.log(fruits); // 输出被修改后的数组:['apple', 'banana', 'kiwi'] fruits.splice(1, 0, 'pear', 'melon'); // 从索引 1 开始插入新元素 console.log(fruits); // 输出被修改后的数组:['apple', 'pear', 'melon', 'banana', 'kiwi'] fruits.splice(4, 1, 'mango'); // 从索引 4 开始替换一个元素 console.log(fruits); // 输出被修改后的数组:['apple', 'pear', 'melon', 'banana', 'mango'] ``` 希望这些示例能够帮助你理解 slicesplice 方法的用法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值