0

我有一个数组 myArray=[1, 2, 3, 4, 5]。我需要从索引 2:3 中获取项目。

在 Python 中,这将是:

my_array = [1, 2, 3, 4, 5]
print(my_array[2:3])

我怎样才能在javascript中完成这个?

4

3 回答 3

1

您可以使用以下.slice功能:

let my_array = [1, 2, 3, 4, 5];
let arr = my_array.slice(2,3);
console.log(arr);

于 2020-08-01T19:39:07.720 回答
1

使用Array.prototype.slice()https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

let my_array = [1, 2, 3, 4, 5]
console.log(my_array.slice(2,3)) // prints '3'
于 2020-08-01T19:42:28.020 回答
0

使用Array.slice(first_index, last_index). 注意at的元素last_index没有返回,所以加1。

如果要返回[3, 4],请使用my_array.slice(2,4). 当然,请记住,数组索引是从零开始的;)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

于 2020-08-01T19:40:43.213 回答