简体   繁体   English

在JavaScript中创建关联数组

[英]Creating associative arrays in JavaScript

Using the following code: 使用以下代码:

$credits.getCredits = function() {
    return $(this).find( 'tbody' ).children( 'tr' ).map(function(){
        var $name = $(this).children(':first').html();
        var $role = $(this).children(':nth-child(2)').html();

        return { $role: $name };
    }).get();
}

Which looks through the elements of a credits list and should return a listing like the following: 这看起来通过信用列表中的元素,而返回类似下面的列表:

[
     { 'Make-up': 'Bob' },
     { 'Make-up': 'Susan' },
     { 'Photography': 'Charlie' },
     { 'Lighting': 'Mike' },
     { 'Props': 'One-handed Tony' }
]

It ends up outputting this instead: 它最终输出这个:

[
     { '$role': 'Bob' },
     { '$role': 'Susan' },
     { '$role': 'Charlie' },
     { '$role': 'Mike' },
     { '$role': 'One-handed Tony' }
]

How do you remedy the associative array creation to get the desired output? 如何修复关联数组创建以获得所需的输出?

Create the object (associative array) in two steps: 分两步创建对象(关联数组):

var obj = {};
obj[$role] = $name;
return obj

Whenever you use literals to create an object ( {foo: bar} ), the key will also be taken literally and will not be evaluated. 每当你使用文字来创建一个对象( {foo: bar} )时,该键也将按字面意思进行,不会被评估。

You need to return it a little differently if you want a dynamic name, like this: 如果你想要一个动态名称,你需要以不同的方式返回它,如下所示:

$credits.getCredits = function() {
  return $(this).find( 'tbody' ).children( 'tr' ).map(function(){
    var $name = $(this).children(':first').html(),
        $role = $(this).children(':nth-child(2)').html(),
        result = {};
    result[$role] = $name;    

    return result;
  }).get();
}

You can try an example here (check the console). 你可以在这里试试一个例子 (检查控制台)。 This is, well, just the way object literal syntax works. 这就是对象文字语法的工作方式。 Since these are equivalent: 因为这些是等价的:

object.propertyName
object["propertyName"]

You can assign via that same route. 您可以通过相同的路线分配。

There are no associative arrays in JS. JS中没有关联数组。 Just create a new object and assign like you want, eg: 只需创建一个新对象并按照您的意愿分配,例如:

var $obj = {};
$obj.MakeUp = 'Bob';

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

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