获取对象在数组中的位置

时间:2015-04-10 20:53:52

标签: javascript jquery arrays

我有一个数组players[]

通过查找其gameSocketId值并返回该对象

从该数组获取某个对象的函数
getUserInfo : function(user)
        {
            var userInfo = Game.players.filter(function(e) {
                return e.gameSocketId === user;
            }).pop();

            return userInfo;
        }

所以我将它存储在像var user = getUserInfo(userId)之类的变量中我怎样才能找出userplayers[]数组中知道所有相关信息的位置是什么?

3 个答案:

答案 0 :(得分:3)

使用.findIndex

getUserInfo : function(user)
    {
        var userInfoIndex = Game.players.findIndex(function(e) {
            return e.gameSocketId === user;
        });

        return userInfoIndex;
    }

请注意,.findIndex虽然完全指定但默认情况下不包含在大多数JS引擎中 - mdn上有一个polyfill:

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.findIndex called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}

这个polyfill适用于ES3和ES5浏览器就好了:))

当然,也可以使用正常的for循环来完成这一过程,这一循环在ES1中一直有效 - 但是你不会得到非常清晰地表达意图的有趣语法:

getUserInfo : function(user) {
    for(var i = 0; i < Game.players.length; i++){
        if(Game.players[i].gameSocketId === user) return i;
    }
    return -1;
}

我们不一定要聪明:) 当然,我们也总是效率低下,只需在使用原始方法获取项目后调用.indexOf

答案 1 :(得分:1)

Array.filter的第二个参数是当前项的索引。下面仍然会返回您最初指定的userInfo以及您可以使用索引的任何内容。

    getUserInfo : function(user)
    {
       var playerIndex;
        var userInfo = Game.players.filter(function(e, index) {
            if (e.gameSocketId === user) {
                playerIndex = index;
                return true;
            }
        }).pop();

        console.log(Game.players[playerIndex]) // <- the player that is also "user"

        return userInfo;
    }

答案 2 :(得分:0)

如何使用indexof()

getUserInfo : function(user){
    var userInfo = Game.players.filter(function(e) {
        return e.gameSocketId === user;
    }).pop();

    return userInfo;
}

// and later
var user = getUserInfo(userId)
console.log(Game.players.indexOf(user));
相关问题