📜  Lodash _.slice()函数

📅  最后修改于: 2022-05-13 01:56:29.318000             🧑  作者: Mango

Lodash _.slice()函数

Lodash是 Node.js 中的一个模块,它工作在 underscore.js 的顶部。 Lodash 有助于处理数组、字符串、对象、数字等。
Lodash.slice()函数用于将数组的切片从起始索引到结束索引,这里结束索引是独占的,开始索引是包含的。

句法:

_.slice(array, startIndex, endIndex)

参数:

  • 数组:这是要从中获取切片的数组。
  • startIndex:数组切片的起始索引。
  • endIndex:切片的结束索引。请注意 endIndex 是专有的。

返回值:返回数组的切片,返回类型为数组。

注意:在使用下面给出的代码之前,请通过npm install lodash安装 lodash 模块。

示例 1:切片数组并且给定的索引大小在数组大小的范围内。

javascript
// Requiring the lodash library
let lodash= require("lodash");
  
// Original array
let array1 = [[1, 12], [12, 8], 7, 8]
  
// Using lodash.slice() method
let newArray = lodash.slice(array1, 1, 3);
  
// Printing original Array
console.log("original Array1: ",array1)
  
// Printing the newArray
console.log("new Array: ", newArray)


javascript
// Requiring the lodash library
let lodash= require("lodash");
  
// Original array
let array1 = [[1, 12], [12, 8], 7, 8, 3, 4]
  
// Using lodash.slice() method
let newArray = lodash.slice(array1, 1, 10);
  
// Printing original Array
console.log("original Array1: ", array1)
  
// Printing the newArray
console.log("new Array: ", newArray)


javascript
// Requiring the lodash library
let lodash = require("lodash");
  
// Original array
let array1 = []
  
// Using lodash.slice() method
let newArray = lodash.slice(array1, 1, 2);
  
// Printing original Array
console.log("original Array1: ", array1)
  
// Printing the newArray
console.log("new Array: ", newArray)


Javascript
// Requiring the lodash library
let lodash = require("lodash");
  
// Original array
let array1 = [1, 2, 4, 3, 1, 5]
  
// Using lodash.slice() method
let newArray = lodash.slice(array1);
  
// Printing original Array
console.log("original Array1: ", array1)
  
// Printing the newArray
console.log("new Array: ", newArray)


输出:

示例 2:切片数组并且给定的结束索引不在数组大小的范围内。

javascript

// Requiring the lodash library
let lodash= require("lodash");
  
// Original array
let array1 = [[1, 12], [12, 8], 7, 8, 3, 4]
  
// Using lodash.slice() method
let newArray = lodash.slice(array1, 1, 10);
  
// Printing original Array
console.log("original Array1: ", array1)
  
// Printing the newArray
console.log("new Array: ", newArray)

输出:

示例 3:
切片空数组

javascript

// Requiring the lodash library
let lodash = require("lodash");
  
// Original array
let array1 = []
  
// Using lodash.slice() method
let newArray = lodash.slice(array1, 1, 2);
  
// Printing original Array
console.log("original Array1: ", array1)
  
// Printing the newArray
console.log("new Array: ", newArray)

输出:

示例 4:当没有给出开始和结束索引时。

Javascript

// Requiring the lodash library
let lodash = require("lodash");
  
// Original array
let array1 = [1, 2, 4, 3, 1, 5]
  
// Using lodash.slice() method
let newArray = lodash.slice(array1);
  
// Printing original Array
console.log("original Array1: ", array1)
  
// Printing the newArray
console.log("new Array: ", newArray)

输出: