获取数组对象的位置 [英] Get objects position in array

查看:187
本文介绍了获取数组对象的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组玩家[]

函数,通过查找 gameSocketId 价值和回报的对象获取某个对象从这样的阵列

function that gets certain object from such array by looking up its gameSocketId value and returns that object

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

            return userInfo;
        }

所以我把它存储在像 VAR用户= getUserInfo(用户ID)我不是如何找出什么是用户的位置<变量/ code>在玩家阵列[] 知道所有关于它的信息?

so I store it in a variable like var user = getUserInfo(userId) How can I than find out what is the position of user in array of players[] knowing all info about it?

推荐答案

使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\"相对=nofollow> .findIndex

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

        return userInfoIndex;
    }

注意 .findIndex ,同时充分规定不包括在大多数JS引擎默认的是 - 没有对<一个一个填充工具href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\"相对=nofollow> MDN :

Note that .findIndex, while fully specified is not included in most JS engines by default yet - there is a polyfill on mdn:

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;
  };
}

本填充工具适用于ES3和ES5浏览器就好了:)

This polyfill works on ES3 and ES5 browsers just fine :)

当然,你也可以使用普通的循环做这其中工程一路过关斩将ES1 - 但你没有得到的乐趣语法传达意图pretty清楚:

Of course, one can also use a normal for loop to do this which works all the way through ES1 - but then you don't get the fun syntax that conveys intent pretty clearly:

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

我们并不总是要聪明:)
当然,我们也可以永远是效率低下,只需要调用 .indexOf 使用原来的方法获取该项目后。

We don't always have to be clever :) Of course, we can also always be inefficient and just call .indexOf after obtaining the item using your original method.

这篇关于获取数组对象的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆