在Loadash中使用slice命令

发布于 2025-01-30 13:15:22 字数 344 浏览 1 评论 0原文

我需要编写一个函数,该函数将有一个数组和一个数字,如果数字为正,则该功能将其放在他的位置,这意味着对于数组1,2,3,4,5,数字2将在第二名。 但是,如果数字为负(例如-2),它将从数组的末尾计数(-2将呈现而不是3)

当前我的代码是:

const _ = require("lodash");

const pleasework = (word,value) => {
_.slice(word, [start=0], [end=value.length]) }
console.log(pleasework((5),[1,2,3,4,5,6,7,8,9]))

很喜欢您的帮助,请提前。

I Need to write a function that thats getting an array and a number, if the number is positive then the function will put it inside his place, which means for the array 1,2,3,4,5 the number 2 will be at the 2nd spot.
but if the number is negative (for example -2) it will be counted from the end of the array (-2 will be presented instead of 3)

currently my code is this:

const _ = require("lodash");

const pleasework = (word,value) => {
_.slice(word, [start=0], [end=value.length]) }
console.log(pleasework((5),[1,2,3,4,5,6,7,8,9]))

would love your help, thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱&纷飞 2025-02-06 13:15:22

如果我正确理解您的问题,即使不使用lodash,您也可以实现它。您可以使用node.js内置方法剪接

您可以阅读有关

let a = [1,2,3,4,5]
const pleaseWork = (word, value) => { 
 let newArray = [...a];
 newArray.splice(value, 0, word);
 return newArray;
}

剪接功能采用三个参数,

  • 第1个位置索引要插入该项目。
  • 第二,您想从数组(可选)
  • 第三中删除多少个元素,您想插入哪个值。

如果第一个元素是负数,它将从末端插入它。

我希望它有帮助。
剪接方法更改原始数组的内容,这就是为什么我创建了一个新数组的原因。

If I've understood your problem correct, You might be able to achieve it even without using lodash. You can use Node.js builtin method splice.

you can read about splice method here.

let a = [1,2,3,4,5]
const pleaseWork = (word, value) => { 
 let newArray = [...a];
 newArray.splice(value, 0, word);
 return newArray;
}

Splice function takes three paramters

  • 1st The positioned index where you want to insert the item.
  • 2nd How many elements you would like to remove from array (optional)
  • 3rd Which value you would like to insert.

If the first element is a negative number it would insert it from the end.

I hope it helps.
The splice method changes the content of original array that is why I have created a new array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文