Home  >  Article  >  Web Front-end  >  Detailed example of the usage of js array method slice()

Detailed example of the usage of js array method slice()

王林
王林forward
2020-03-07 10:50:436276browse

Detailed example of the usage of js array method slice()

slice() method introduction

slice(), which can create 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.

(Recommended learning: javascript tutorial)

The example is 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:

Detailed example of the usage of js array method slice()

For more programming-related tutorials, please pay attention to the Programming Introduction column on the php Chinese website!

The above is the detailed content of Detailed example of the usage of js array method slice(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete