作为一名 javascript 开发人员,我经常发现两个数组方法有点难以掌握/完全掌握
因此,我决定深入研究并用清晰的示例来分解这些方法。
如果我重写语法
数组.切片
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);
注意:-
让我们看一些例子:-
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 ]
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' ]
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' ]
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' ]
以上就是Arrayslice 与 Arraysplice:消除混淆的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号