我有一个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
语法
arr.slice([begin[, end]])
。
end
可选结束提取的从零开始的索引。
slice
提取到但不包括结束。例如,
slice(1,4)
通过第四个元素(索引为 1、2 和 3 的元素)提取第二个元素。可以使用负索引,指示与序列末尾的偏移量。
slice(2,-1)
通过序列中的倒数第二个元素提取第三个元素。如果省略
end
,则slice
通过序列末尾提取 (arr.length
)。如果
end
大于序列的长度,则slice
提取到序列的末尾 (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);
要slice()
的第二个参数是结束索引。 所以你的意思是给我从i
到索引 3(不包括)的所有元素。
你应该说的是slice(i, i+3)
slice(i, 3)
基本上意味着你想要一个新的数组,在索引i
之前的索引和索引3
之间有元素。您可以使用一个简单的for loop
来返回每个元素的前面的两个元素,如下所示:
var arr = [1,2,3,4,5,6,7,8,9]
function get(x){
for (i = 0; i < x.length - 2; i++){
console.log("The proceeding two elements of " + x[i] + " is " + x[i+1] + " and " + x[i+2]);
}
}
get(arr);
注:注:for 循环x.length - 2
中的- 2
是防止返回未定义的结果,因为最后两个元素不会有两个进行元素。
或者,如果您更喜欢使用 slice()
,您可以这样做:
var arr = [1,2,3,4,5,6,7,8,9]
function get(x){
for (i = 0; i < x.length - 2; i++){
console.log(x.slice(i, i+3));
}
}
get(arr);
同样,for 循环x.length - 2
中的- 2
是防止返回未定义的结果或不完整的结果,因为最后两个元素不会有两个后续元素。