获取对象在数组中的位置

我有arraysplayers[]

通过查找其gameSocketId值并返回该对象来从此类数组中获取特定对象的函数

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

所以我将它存储在一个变量中,如var user = getUserInfo(userId)我怎样才能找出players[]arrays中user的位置players[]知道所有关于它的信息?

使用.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

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

如何使用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));