在 JavaScript 中创建关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3275633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:59:04  来源:igfitidea点击:

Creating associative arrays in JavaScript

javascriptjqueryassociative-array

提问by Metalshark

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 shouldreturn 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?

您如何补救关联数组的创建以获得所需的输出?

回答by Felix Kling

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}) 时,键也将按字面意思使用,不会被计算。

回答by Nick Craver

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.

您可以通过相同的路线进行分配。

回答by Mene

There are no associative arrays in JS. Just create a new object and assign like you want, e.g:

JS 中没有关联数组。只需创建一个新对象并根据需要进行分配,例如:

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