📜  Lodash _.dropRight()函数

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

Lodash _.dropRight()函数

Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、字符串、对象、数字等。
_.dropRight()函数用于从数组右侧删除元素,即从第 (n-1) 个元素中删除。

句法:

_.dropRight(array, n)

范围:

  • 数组:它是要从中删除元素的原始数组。
  • n:这里 n 是要从数组中删除的元素的数量。默认情况下,它设置为 1。

返回值:返回数组。

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

示例 1:当 n 小于数组的大小时。

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

输出:

示例 2:当 n 大于数组的大小时。

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

输出:

示例 3:当给定对象数组但未给出 n 时。

// Requiring the lodash library
const _ = require("lodash");
  
// Original array
let array1 = [
    { "a": 1, "b": 2 }, 
    { "a": 2, "b": 1 }, 
    { "b": 2 }
]
  
// Using _.dropRight() function
let newArray = lodash.dropRight(array1);
  
// Original Array
console.log("original Array: ", array1)
  
// Printing the newArray
console.log("new Array: ", newArray)

输出: