在 JavaScript 中创建关联数组
使用以下代码:
$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();
}
它会查看学分列表的元素,并且应该返回如下所示的列表:
[
{ 'Make-up': 'Bob' },
{ 'Make-up': 'Susan' },
{ 'Photography': 'Charlie' },
{ 'Lighting': 'Mike' },
{ 'Props': 'One-handed Tony' }
]
它最终会输出以下内容:
[
{ '$role': 'Bob' },
{ '$role': 'Susan' },
{ '$role': 'Charlie' },
{ '$role': 'Mike' },
{ '$role': 'One-handed Tony' }
]
如何补救关联数组创建以获得所需的输出?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
分两步创建对象(关联数组):
每当您使用文字创建对象(
{foo: bar}
)时,键也将按字面意思获取,并且不会被求值。Create the object (associative array) in two steps:
Whenever you use literals to create an object (
{foo: bar}
), the key will also be taken literally and will not be evaluated.如果您想要动态名称,则需要以稍微不同的方式返回它,如下所示:
您可以在此处尝试一个示例(检查控制台)。这就是对象字面量语法的工作方式。由于它们是等效的:
您可以通过相同的路线进行分配。
You need to return it a little differently if you want a dynamic name, like this:
You can try an example here (check the console). This is, well, just the way object literal syntax works. Since these are equivalent:
You can assign via that same route.
JS 中没有关联数组。只需创建一个新对象并根据需要进行分配,例如:
There are no associative arrays in JS. Just create a new object and assign like you want, e.g: