【问题标题】:Javascript:Select from array.push()Javascript:从 array.push() 中选择
【发布时间】:2014-01-30 00:41:44
【问题描述】:

我有这个 array.push 函数:

users.push({
    username: username,
    rank: 0
});

我需要选择用户数组中有多少个用户名:

console.log(username + " joined the chat. "+ users[username].length +" chatters online now!");

但这不起作用:

无法读取未定义的“长度”属性

那么,如何选择用户名呢?

【问题讨论】:

  • users 不是关联数组。为什么不只检查users 数组的.length 属性?
  • users.length可以包含用户数。

标签: javascript arrays node.js


【解决方案1】:

我怀疑users.length 可以解决问题,因为您使用push 函数表明users 是一个线性或非关联数组。但是,如果您想找出 users 数组中有多少对象实际上定义了 username 属性,您需要循环遍历它:

var i = users.length,
    usernameLength;

while(i--) {
    if(users[i].username !== undefined) {
        usernameLength++;
    }
}

// usernameLength represents the amount of users in the users array that have defined usernames
username + " joined the chat. "+ usernameLength +" chatters online now!");

【讨论】:

  • +1 以区别于其他答案,因为正确。也是一个简短的提示。你不需要typeof 检查 - 你可以做users[i].username !== undefined。甚至更好 - users.filter(function(user){ return users[i].username; })
  • 谢谢。你是对的。 typeof 检查是纯粹的习惯力量。 :)
  • 有效,但是如何获取用户名的索引?
  • 这取决于。您要查找哪个用户名的索引?
【解决方案2】:

你推送一个对象,users 是一个以数字为键的数组,每个元素都是对象,用户名和排名作为参数。

试试:users[0].username.

【讨论】:

    【解决方案3】:

    如果会使用filter 创建一个包含所有具有用户名的对象的新数组,并计算该长度:

    var filtered = users.filter(function (user) {
      return user.username && user.username.length > 0;
    });
    
    console.log(filtered.length);
    

    一行:

    var length = (users.filter(function (user) { return user.username && user.username.length > 0 })).length
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      相关资源
      最近更新 更多