获取除first和last之外的所有数组元素

时间:2022-12-09 20:54:00

I have an array of locations, I need to be able to access origin, middlepoints and destination separately.

我有一系列的位置,我需要能够分别访问原点,中点和目的地。

I know that my origin is always the first element and the destination is always the last element but I cant figure out how can I dynamically can access all the middlepoints.

我知道我的起源始终是第一个元素,目的地始终是最后一个元素,但我无法弄清楚如何动态地访问所有中间点。

3 个解决方案

#1


8  

To achieve this you can use shift() and pop() to get the first and last elements of the array, respectively. Whatever is left in the array after those operations will be your 'middlepoints'. Try this:

要实现这一点,您可以使用shift()和pop()分别获取数组的第一个和最后一个元素。在这些操作之后,数组中剩下的是你的“中间点”。试试这个:

var middlePoints = ['start', 'A', 'B', 'C', 'end'];
var origin = middlePoints.shift();
var destination = middlePoints.pop();

console.log(origin);
console.log(middlePoints);
console.log(destination);

#2


8  

Since there is no data I am taking a basic array to show. Also by this method you will preserve your original array.

由于没有数据我正在使用基本数组来显示。此外,通过此方法,您将保留原始数组。

var arr = [1,2,3,4,5,6,7];
var middle = arr.slice(1, arr.length-1);
console.log(middle);

#3


1  

Something like this?

像这样的东西?

var allPoints = [0, 1, 2, 3, 4, 5],
    midPoints = []

/*start the iteration at index 1 instead of 0 since we want to skip the first point anyway and stop iteration before the final item in the array*/
for (var i = 1; i < (allPoints.length - 1); i++) {
  midPoints.push(allPoints[i]);
}

console.log(midPoints);

#1


8  

To achieve this you can use shift() and pop() to get the first and last elements of the array, respectively. Whatever is left in the array after those operations will be your 'middlepoints'. Try this:

要实现这一点,您可以使用shift()和pop()分别获取数组的第一个和最后一个元素。在这些操作之后,数组中剩下的是你的“中间点”。试试这个:

var middlePoints = ['start', 'A', 'B', 'C', 'end'];
var origin = middlePoints.shift();
var destination = middlePoints.pop();

console.log(origin);
console.log(middlePoints);
console.log(destination);

#2


8  

Since there is no data I am taking a basic array to show. Also by this method you will preserve your original array.

由于没有数据我正在使用基本数组来显示。此外,通过此方法,您将保留原始数组。

var arr = [1,2,3,4,5,6,7];
var middle = arr.slice(1, arr.length-1);
console.log(middle);

#3


1  

Something like this?

像这样的东西?

var allPoints = [0, 1, 2, 3, 4, 5],
    midPoints = []

/*start the iteration at index 1 instead of 0 since we want to skip the first point anyway and stop iteration before the final item in the array*/
for (var i = 1; i < (allPoints.length - 1); i++) {
  midPoints.push(allPoints[i]);
}

console.log(midPoints);