洛達什是Node.js中的一個模塊,可在underscore.js的頂部使用。 Lodash幫助處理數組,字符串,對象,數字等。
Lodash.slice()函數用於從開始索引到結束索引獲取數組的切片,這裏結束索引是排他的,開始索引是包含的。
用法:
_.slice(array, startIndex, endIndex)
參數:
- array:它是要從中獲取切片的數組。
- startIndex:它是數組切片開始的起始索引。
- endIndex:它是切片的最終索引。請注意,endIndex是排他性的。
返回值:它返回數組的切片,返回類型為array。
注意:在使用以下給定代碼之前,請先通過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)
輸出:
範例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)
輸出:
相關用法
- Node.js slice()用法及代碼示例
- PHP Ds\Sequence slice()用法及代碼示例
- PHP Ds\Vector slice()用法及代碼示例
- PHP Ds\Deque slice()用法及代碼示例
- PHP Ds\Set slice()用法及代碼示例
- Tensorflow.js tf.slice()用法及代碼示例
- JavaScript Array slice()用法及代碼示例
- Javascript string.slice()用法及代碼示例
- Javascript typedArray.slice()用法及代碼示例
- JQuery slice()用法及代碼示例
- CSS border-image-slice用法及代碼示例
- Node.js Buffer.slice()用法及代碼示例
- Javascript Array.slice()和Array.splice()的區別用法及代碼示例
- Typescript String slice()用法及代碼示例
- Typescript Array slice()用法及代碼示例
- underscore.js _.iterators.slice()用法及代碼示例
- Collect.js slice()用法及代碼示例
- Lodash _.tail()用法及代碼示例
- Node.js lodash.sortBy()用法及代碼示例
- Lodash _.difference()用法及代碼示例
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 Lodash _.slice() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。