gpt4 book ai didi

javascript - 从 JavaScript 数组中获取接下来的两个后续元素

转载 作者:行者123 更新时间:2023-11-30 19:55:29 25 4
gpt4 key购买 nike

我有一个javascript数组 我希望使用函数和切片获取下一个前面的两个元素。我没有得到结果。有什么办法可以解决这个问题吗?

 var arr = [1,2,3,4,5,6,7,8,9]

function get(arr){
for(var i=0; i<arr.length; i++){
console.log(arr.slice(i, 3))
}}


// Now when I call the function

get(arr)

// Funny output

[1, 2, 3]
[2, 3]
[3]
[]
[]
[]
[]
[]
[]
[]
[]

最佳答案

您需要索引而不是长度 Array#slice

Syntax

arr.slice([begin[, end]])

...

end Optional

Zero-based index before which to end extraction. slice extracts up to but not including end.

For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).

A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.

If end is omitted, slice extracts through the end of the sequence (arr.length).

If end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length).

function get(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr.slice(i, i + 3));
}
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

get(arr);

关于javascript - 从 JavaScript 数组中获取接下来的两个后续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54046566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com