首页 > web前端 > js教程 > 正文

Array.slice 与 Array.splice:消除混淆

PHPz
发布: 2024-08-09 14:33:07
原创
253 人浏览过

Array.slice vs. Array.splice: Clearing Up the Confusion

介绍

作为一名 JavaScript 开发人员,我经常发现两个数组方法有点难以掌握/完全

  1. 数组.slice
  2. 数组.splice。

因此,我决定深入研究并用清晰的示例来分解这些方法。

如果我重写语法

Array.slice

returns the deleted elements in a form of Array = Array.prototype.slice(startIndex, endIndex-1);
登录后复制

Array.splice(P 代表永久 - 永远记住)

JavaScript 中的 splice 方法通过删除或替换现有元素和/或添加新元素来修改数组的内容

删除元素语法

returns the deleted elements in a form of Array = Array.prototype.splice(startIndex, endIndex-1); // permanent 

登录后复制

添加元素语法

array.splice(startIndex, 0, item1, item2, ..., itemX);
登录后复制

注意:-

  1. 它更改原始数组并返回删除的数组。

  2. 当它表现为添加操作时,它会返回 [],因为它没有删除任何内容。

让我们看一些例子:-

Q1。练习 1 - 使用切片获取数组的一部分:创建一个包含从 1 到 10 的数字的数组。使用切片方法获取包含从 4 到 8 的数字的新数组。

const arr = Array.from(Array(10), (_, i) => i+1);
console.log('Array --> ', arr);
console.log('get a new array that includes numbers from 4 to 8 --> ', arr.slice(3, 8)); // Array.prototype.slice(startIndex, endIndex-1);

// [ 4, 5, 6, 7, 8 ]
登录后复制

Q2。练习 2 - 使用 splice 从数组中删除元素:创建一个水果数组。使用 splice 方法从数组中删除“苹果”和“香蕉”。

const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];

fruits.splice(0, 2)// permanent

console.log('splice method to remove "apple" and "banana" from the array. --> ', fruits);

// [ 'orange', 'mango', 'kiwi' ]
登录后复制

Q3。练习 3 - 使用 splice 将元素添加到数组中:创建颜色数组。使用拼接的方法在“红色”后面添加“粉色”和“紫色”。

const colors = ['red', 'green', 'blue'];

const y = colors.splice(1, 0, "pink", "purple"); /
console.log(y); // [] see above to see why.
console.log('splice method to add "pink" and "purple" after "red" --> ', colors)

// [ 'red', 'pink', 'purple', 'green', 'blue' ]
登录后复制

第四季度。练习 4 - 使用切片和拼接:创建一个从“a”到“e”的字母数组。使用 slice 获取前三个字母的新数组。然后在原始数组上使用 splice 删除这些字母。

const letters = ['a', 'b', 'c', 'd', 'e'];
const newSlice = letters.slice(0, 3);
const x = letters.splice(0, 3);
console.log(x);
console.log('slice to get a new array of the first three letters --> ', newSlice) // [ 'a', 'b', 'c' ]

console.log('Then use splice on the original array to remove these letters --> ', letters)[ 'd', 'e' ]
登录后复制

如果您有任何疑问/疑虑,请随时与我联系。

以上是Array.slice 与 Array.splice:消除混淆的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!