javascript 从 underscore.js 中的数组返回一系列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10093642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:40:21  来源:igfitidea点击:

return a range of values from an array in underscore.js

javascriptjquerybackbone.jsunderscore.js

提问by cherit

I have an array with the following data

我有一个包含以下数据的数组

var a = [1,2,3,4,5,6,7]

I am looking for a method in underscore.js or backbone.js in which I can return the elements with a specified range. for ex:

我正在underscore.js 或backbone.js 中寻找一种方法,我可以在其中返回具有指定范围的元素。例如:

filter(2,5) should return  [3,4,5,6] 

which is the 2nd to 5th index elements in the array. Any pointers for me ?

这是数组中的第 2 到第 5 个索引元素。对我有什么建议吗?

回答by Selvakumar Arumugam

Javascript Array should be defined like below,

Javascript Array 应该像下面这样定义,

var a = [1,2,3,4,5,6,7]; //not inside {}

And then you can use array native slicemethod to get elements from a specific position

然后你可以使用数组原生切片方法从特定位置获取元素

a.slice(2, 6) //should return 3,4,5,6

Edit:

编辑:

I very well know that the functionality is available in JScript. I was asking if its available in backbone or underscore. You are asking like why would you want an ice cube instead of water because ice will turn to water eventually.

我非常清楚该功能在 JScript 中可用。我在问它是否可以在主干或下划线中使用。你在问为什么你想要冰块而不是水,因为冰最终会变成水。

Underscore js do nothave function like sliceas it is already available in native js.

Underscore js没有slice原生 js 那样的功能。

回答by Nahn

Step 1:

步骤1:

Switch to Lodash. (https://lodash.com/)

切换到 Lodash。( https://lodash.com/)

Note: dangerous step, you will never go back.

注意:危险的一步,你永远不会回头。

Step 2:

第2步:

Use the _.slicefunction like this:

_.slice像这样使用函数:

_.slice(a, 2, 5)

_.slice(a, 2, 5)