【问题标题】:Get items in array from index 2:3 [duplicate]从索引2:3获取数组中的项目[重复]
【发布时间】:2020-08-01 19:37:28
【问题描述】:

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

在 Python 中,这将是:

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

如何在 javascript 中完成此操作?

【问题讨论】:

  • 你可以使用.slice

标签: javascript


【解决方案1】:

你可以使用.slice函数:

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

【讨论】:

    【解决方案2】:

    使用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'
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-05
        • 2013-04-29
        • 2011-01-28
        • 2018-11-23
        • 2015-07-12
        相关资源
        最近更新 更多