卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章72734本站已运行431

Arrayslice 与 Arraysplice:消除混淆

arrayslice 与 arraysplice:消除混淆

介绍

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

  1. 数组.切片
  2. 数组.splice。

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

如果我重写语法

数组.切片

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 ]
第二季度。练习 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' ]
第三季度。练习 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' ]
如果您有任何疑问/疑虑,请随时与我联系。

卓越飞翔博客
上一篇: 充分利用小空间:巧妙的存储解决方案
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏