Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - Get objects position in array

I have an array players[]

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use .findIndex:

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

        return userInfoIndex;
    }

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

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...