选择 JavaScript 数组中的最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9050345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:30:02  来源:igfitidea点击:

Selecting last element in JavaScript array

javascriptarraysgoogle-mapsgoogle-maps-markers

提问by mkyong

I'm making an application that updates a user's location and path in real time and displays this on a Google Map. I have functionality that allows multiple users to be tracked at the same time using an object, which is updated every second.

我正在制作一个应用程序,可以实时更新用户的位置和路径,并将其显示在 Google 地图上。我的功能允许使用一个对象同时跟踪多个用户,该对象每秒更新一次。

Right now, when a user pressed a button in the Android app, the coordinates are sent to a database and each time the location changes, a marker is updated on the map (and a polyline is formed).

现在,当用户按下 Android 应用程序中的按钮时,坐标被发送到数据库,每次位置发生变化时,地图上的标记都会更新(并形成多段线)。

Since I have multiple users, I send a unique and randomly generated alphanumeric string so that I can display an individual path for each user. When the JS pulls this data from the database, it checks if the user exists, if it does not, it creates a new key with the value being a list. It would look something like this:

由于我有多个用户,因此我发送了一个唯一且随机生成的字母数字字符串,以便我可以为每个用户显示单独的路径。当 JS 从数据库中提取此数据时,它会检查用户是否存在,如果不存在,则创建一个值为列表的新键。它看起来像这样:

loc = {f096012e-2497-485d-8adb-7ec0b9352c52: [new google.maps.LatLng(39, -86),
                                              new google.maps.LatLng(38, -87),
                                              new google.maps.LatLng(37, -88)],
       44ed0662-1a9e-4c0e-9920-106258dcc3e7: [new google.maps.LatLng(40, -83),
                                              new google.maps.LatLng(41, -82),
                                              new google.maps.LatLng(42, -81)]}

What I'm doing is storing a list of coordinates as the value of the key, which is the user's ID. My program keeps updating this list each time the location is changed by adding to the list (this works properly).

我正在做的是将坐标列表存储为键的值,即用户的 ID。每次通过添加到列表来更改位置时,我的程序都会不断更新此列表(这可以正常工作)。

What I need to do is update the marker's location each time the location changes. I would like to do this by selecting the last item in the array since that would be the last known location. Right now, each time the location is changed a new marker is added to the map (each one of the points in the example would show a marker at that location) so markers continue to be added.

我需要做的是每次位置更改时更新标记的位置。我想通过选择数组中的最后一项来做到这一点,因为那将是最后一个已知位置。现在,每次更改位置时,都会向地图添加一个新标记(示例中的每个点都会在该位置显示一个标记),因此会继续添加标记。

I would use a ′for (x in loc)` statement each time the location updates to grab the last location from the list and use that to update the marker. How do I select this last element from the array within the hash?

每次位置更新时,我都会使用“for (x in loc)”语句从列表中获取最后一个位置并使用它来更新标记。如何从散列中的数组中选择最后一个元素?

回答by Tadeck

How to access last element of an array

如何访问数组的最后一个元素

It looks like that:

它看起来像这样:

var my_array = /* some array here */;
var last_element = my_array[my_array.length - 1];

Which in your case looks like this:

在你的情况下看起来像这样:

var array1 = loc['f096012e-2497-485d-8adb-7ec0b9352c52'];
var last_element = array1[array1.length - 1];

or, in longer version, without creating new variables:

或者,在更长的版本中,不创建新变量:

loc['f096012e-2497-485d-8adb-7ec0b9352c52'][loc['f096012e-2497-485d-8adb-7ec0b9352c52'].length - 1];

How to add a method for getting it simpler

如何添加方法使其更简单

If you are a fan for creating functions/shortcuts to fulfill such tasks, the following code:

如果您喜欢创建函数/快捷方式来完成此类任务,请使用以下代码:

if (!Array.prototype.last){
    Array.prototype.last = function(){
        return this[this.length - 1];
    };
};

will allow you to get the last element of an array by invoking array's last()method, in your case eg.:

将允许您通过调用数组的last()方法来获取数组的最后一个元素,例如:

loc['f096012e-2497-485d-8adb-7ec0b9352c52'].last();

You can check that it works here: http://jsfiddle.net/D4NRN/

你可以在这里检查它是否有效:http: //jsfiddle.net/D4NRN/

回答by Datageek

Use the slice()method:

使用slice()方法:

my_array.slice(-1)[0]

回答by Josh

You can also .popoff the last element. Be careful, this will change the value of the array, but that might be OK for you.

您也可以.pop关闭最后一个元素。小心,这会改变 array 的值,但这对你来说可能没问题。

var a = [1,2,3];
a.pop(); // 3
a // [1,2]

回答by hamecoded

use es6 deconstruction array with the spread operator

使用带有扩展运算符的 es6 解构数组

var last = [...yourArray].pop();

var last = [...yourArray].pop();

note that yourArray doesn't change.

请注意, yourArray 不会改变。

回答by Nery Jr

var arr = [1, 2, 3];
arr.slice(-1).pop(); // return 3 and arr = [1, 2, 3]

This will return undefined if the array is empty and this will not change the value of the array.

如果数组为空,这将返回 undefined 并且这不会更改数组的值。

回答by amay0048

var last = array.slice(-1)[0];

I find slice at -1 useful for getting the last element (especially of an array of unknown length) and the performance is much better than calculating the length less 1.

我发现 -1 处的切片对于获取最后一个元素(尤其是未知长度的数组)很有用,并且性能比计算长度小于 1 好得多。

Mozilla Docs on Slice

切片上的 Mozilla 文档

Performance of the various methods for selecting last array element

选择最后一个数组元素的各种方法的性能

回答by svarog

Underscoreand Lodashhave the _.last(Array)method, that returns the last element in an Array. They both work about the same

下划线Lodash_.last(Array)方法,即返回数组中的最后一个元素。它们的工作方式大致相同

_.last([5, 4, 3, 2, 1]);
=> 1

Ramdaalso has a _.lastfunction

Ramda也有一个_.last功能

R.last(['fi', 'fo', 'fum']); //=> 'fum'

回答by Levi Morrison

Use JavaScript objects if this is critical to your application.You shouldn't be using raw primitives to manage critical parts of your application. As this seems to be the core of your application, you should use objects instead. I've written some code below to help get you started. The method lastLocationwould return the last location.

如果这对您的应用程序至关重要,请使用 JavaScript 对象。您不应该使用原始原语来管理应用程序的关键部分。由于这似乎是您的应用程序的核心,因此您应该改用对象。我在下面编写了一些代码来帮助您入门。该方法lastLocation将返回最后一个位置。



function User(id) {
    this.id = id;

    this.locations = [];

    this.getId = function() {
        return this.id;
    };

    this.addLocation = function(latitude, longitude) {
        this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
    };

    this.lastLocation = function() {
        return this.locations[this.locations.length - 1];
    };

    this.removeLastLocation = function() {
        return this.locations.pop();
    };

}

function Users() {
    this.users = {};

    this.generateId = function() {
        return Math.random();
    };

    this.createUser = function() {
        var id = this.generateId();
        this.users[id] = new User(id);
        return this.users[id];
    };

    this.getUser = function(id) {
        return this.users[id];
    };

    this.removeUser = function(id) {
        var user = this.getUser(id);
        delete this.users[id];

        return user;
    };

}


var users = new Users();

var user = users.createUser();

user.addLocation(0, 0);
user.addLocation(0, 1);

回答by X?pplI'-I0llwlg'I -

You can define a getteron Array.prototype:

您可以在 上定义一个吸气剂Array.prototype

if (!Array.prototype.hasOwnProperty("last")) {
  Object.defineProperty(Array.prototype, "last", {
    get() {
      return this[this.length - 1];
    }
  });
}

console.log([9, 8, 7, 6].last); // => 6

As you can see, access doesn't look like a function call; the getter function is called internally.

如您所见,访问看起来不像函数调用;getter 函数在内部调用。

回答by Mykhailo Zhuk

In case you are using ES6 you can do:

如果您使用的是 ES6,您可以执行以下操作:

const arr = [ 1, 2, 3 ];
[ ...arr ].pop(); // 3
arr; // [ 1, 2, 3 ] (wasn't changed)