简体   繁体   English

javascript:对象可以从字面上替换数组吗?

[英]javascript: can object literally replace array?

Say I just want a variable to hold a bunch of information, and the order is not important . 假设我只希望变量包含一堆信息,并且顺序并不重要 For example, i have a variable players that hold all the information of players in a game. 例如,我有一个可变的players ,可以容纳游戏中所有玩家的信息。 If I use an object to hold all the information, isn't it better than using an array to do so in every possible way? 如果我使用一个对象来保存所有信息,这难道不比使用数组以各种可能的方式保存信息更好吗?

var players = [{ name: 'john', age: '10' }, { name: 'lily', age: '11' }];

versus

var players = { john: { name: 'john', age: '10' }, lily: { name: 'lily', age: '11' } };

If I count the number of players, or to access/edit a player's information directly, isn't using object better than array in every possible way? 如果我计算播放器的数量,或者直接访问/编辑播放器的信息,不是在所有可能的方式上使用对象都优于数组吗?

If so, can object literally replace array in any non-ordered situation? 如果是这样,对象可以在任何无序情况下按字面替换数组吗?

You lose access to all of the built-in array methods. 您将无法访问所有内置数组方法。 What if you ever wanted a sorted list? 如果您想要排序列表怎么办? I can imagine dozens of scenarios where you would want to have an Array. 我可以想象您想拥有一个阵列的数十种情况。

What do you gain? 你得到什么? Access to objects in your array by name? 通过名称访问数组中的对象? Arrays are objects, so you can just extend the array to get that: 数组是对象,因此您只需扩展数组即可:

var players = [{ name: 'john', age: '10' }, { name: 'lily', age: '11' }];
players.forEach(function (player) {
    players[player.name] = player;
});
console.log(player[0] === player.john); // true!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM