JavaScript 数组:获取“范围”项目数

发布于 2024-09-15 20:58:53 字数 180 浏览 4 评论 0 原文

JavaScript 中是否有与 ruby​​ 的 array[n..m] 等效的东西?

例如:

>> a = ['a','b','c','d','e','f','g']
>> a[0..2]
=> ['a','b','c']

Is there an equivalent for ruby's array[n..m] in JavaScript?

For example:

>> a = ['a','b','c','d','e','f','g']
>> a[0..2]
=> ['a','b','c']

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

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

发布评论

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

评论(4

怀里藏娇 2024-09-22 20:58:53

使用 array.slice(begin [, end])函数。

var a = ['a','b','c','d','e','f','g'];
var sliced = a.slice(0, 3); //will contain ['a', 'b', 'c']

最后一个索引是非包含的;要模仿 ruby​​ 的行为,您必须增加 end 值。所以我猜 slice 的行为更像 ruby​​ 中的 a[m...n]

Use the array.slice(begin [, end]) function.

var a = ['a','b','c','d','e','f','g'];
var sliced = a.slice(0, 3); //will contain ['a', 'b', 'c']

The last index is non-inclusive; to mimic ruby's behavior you have to increment the end value. So I guess slice behaves more like a[m...n] in ruby.

隔岸观火 2024-09-22 20:58:53

slice 中的第二个参数也是可选的:

var fruits = ['apple','banana','peach','plum','pear'];
var slice1 = fruits.slice(1, 3);  //banana, peach
var slice2 = fruits.slice(3);  //plum, pear

您还可以传递一个负数,该负数从数组的末尾进行选择:

var slice3 = fruits.slice(-3);  //peach, plum, pear

这是 W3 Schools 参考 链接

The second argument in slice is optional, too:

var fruits = ['apple','banana','peach','plum','pear'];
var slice1 = fruits.slice(1, 3);  //banana, peach
var slice2 = fruits.slice(3);  //plum, pear

You can also pass a negative number, which selects from the end of the array:

var slice3 = fruits.slice(-3);  //peach, plum, pear

Here's the W3 Schools reference link.

轻许诺言 2024-09-22 20:58:53

a.slice(0, 3) Would be the equivalent of your function in your example.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice

稀香 2024-09-22 20:58:53

Ruby 和 Javascript 都有 slice 方法,但要小心Ruby 中 slice 的第二个参数是长度,但在 JavaScript 中它是最后一个元素的索引:

var shortArray = array.slice(start, end);

Ruby and Javascript both have a slice method, but watch out that the second argument to slice in Ruby is the length, but in JavaScript it is the index of the last element:

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