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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…