The following article will analyze how to use the array method slice() in JavaScript through examples. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "javascript video tutorial"
slice() method introduction
slice(), which creates a new array based on one or more elements in the current array. Can accept one or two parameters, the starting and ending positions to be returned.
One parameter: The slice() method returns all items starting from the position specified by the parameter to the end of the current array.
Two parameters: This method returns the items between the start and end positions (but not including the items at the end position).
slice does not affect the original array.
The end position is less than the starting position, and an empty array is returned.
You can accept negative numbers, and use the length of the array plus the negative number to determine the corresponding position.
The examples are as follows:
var arr = [1, 2, 3, 'a', 'b', 'c', 'd']; Array.prototype.copySlice =function() { var newArr = []; var len = this.length; var argLen = arguments.length; if(arguments.length == 1) {//一个参数 var startNum = arguments[0] > 0 ? arguments[0] : (len + arguments[0]); for(var i = startNum; i < len; i++) { newArr.push(arr[i]); } } else if(arguments.length == 2) {//两个参数 var startNum = arguments[0] > 0 ? arguments[0] : (len + arguments[0]); var endNum = arguments[1] > 0 ? arguments[1] : (len + arguments[1]); if(startNum >= endNum) {//起始索引大于终止索引,返回[] return newArr; } else { for(var i = startNum; i < endNum; i++) { newArr.push(arr[i]); } } } return newArr; }; console.log(arr.length); // 7 // 一个参数 console.log(arr.copySlice(2)); // [3, "a", "b", "c", "d"] // 两个参数 console.log(arr.copySlice(3, 6)); //["a", "b", "c"] console.log(arr); //[1, 2, 3, "a", "b", "c", "d"] // 接收负数 console.log(arr.copySlice(-2)); // ["c", "d"] console.log(arr.copySlice(-5, 6)); //[3, "a", "b", "c"] //结束位置小于起始位置,返回空数组。 console.log(arr.copySlice(-5, -6)); //[] console.log(arr.copySlice(5, 5)); //[] console.log(arr.copySlice(5, )); // ["c", "d"]
Part of the running results are as shown in the figure:
##For more programming-related knowledge, please visit:Programming getting Started! !
The above is the detailed content of Learn how to use JavaScript array method slice() through examples. For more information, please follow other related articles on the PHP Chinese website!