<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> /* * splice(start, deleteCount, data1, data2, data3...) * */ var arr = ['a', 'b', 'c', 'd', 'e']; //1, 3 // [8,6,4] //['a',8,6,4] //arr.splice(-5); //console.log(arr); function arrSplice(data, start, deleteCount) { // 如果start不是数字,或不能转成数字,start默认就为0 if (isNaN(start)) { start = 0; } start = Number(start); // 如果start是负数 if (start < 0) { start = data.length + start; } if (start < 0) { start = 0; } // 如果deleteCount没传 if (deleteCount == undefined) { deleteCount = data.length - start; } /* * 1. 准备一个空的数组,用于存放最后的结果 * 2. 循环源数组 * 1. 得到当前循环过程中的下标 * 2. 把这个下标和start做比较 * 1. 如果当前下标小于start,则把当前数组添加到新数组中 * 2. 否则 * 1. 是否有新增数据 * 1. 如果有新在数据,则把新增数据添加到新数组中 * 2. 否则,如果deleteCount大于0,忽略这个数据,并对deleteCount-- * 否则,把当前数据添加到新数组中 * */ var newArr = []; //新增数据 var newData = []; if (arguments.length > 3) { for (var i=3; i<arguments.length; i++) { // newData.push(arguments[i]); newData[newData.length] = arguments[i]; } } for (var i=0; i<data.length; i++) { if (i < start) { // newArr.push(data[i]); newArr[newArr.length] = data[i]; } else { if (newData.length) { //有新增数据的 // newArr = newArr.concat(newData); for (var j=0; j<newData.length; j++) { newArr[newArr.length] = newData[j]; } newData.length = 0; } if (deleteCount > 0) { deleteCount--; } else { // newArr.push(data[i]); newArr[newArr.length] = data[i]; } } } data = newArr; console.log(data); } </script> </body> </html>
The above is the detailed content of JS native array splice method instance. For more information, please follow other related articles on the PHP Chinese website!