本文介绍了使Javascript做列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的方法是让Javascript做什么喜欢 Python的列表理解?

What is the cleanest way to make Javascript do something like Python's list comprehension?

在Python中如果我有一个对象列表name我希望'拉出'我会这样做...

In Python if I have a list of objects whose name's I want to 'pull out' I would do this...

list_of_names = [x.name for x in list_of_objects]

在javascript中我真的没有看到更好的方式做到这一点而不仅仅是使用一个for循环结构。

In javascript I don't really see a more 'beautiful' way of doing that other than just using a for loop construct.

FYI:我正在使用jQuery;也许它有一些漂亮的功能,使这成为可能?

FYI: I'm using jQuery; maybe it has some nifty feature that makes this possible?

更具体地说,我使用像 $('input')这样的jQuery选择器来获取所有输入元素,我将如何最干净地为每个元素创建一个包含所有 name 属性的数组输入元素 - 即所有 $('input')。attr('name')字符串in一个数组?

More specifically, say I use a jQuery selector like $('input') to get all input elements, how would I most cleanly create an array of all the name attributes for each of these input elements--i.e., all of the $('input').attr('name') strings in an array?

推荐答案

使用,需要javascript 1.6(这意味着,适用于每个浏览器,但IE< 9),带有像MooTools这样的对象扩充框架在每个浏览器上:

generic case using Array.map, requires javascript 1.6 (that means, works on every browser but IE < 9) or with an object augmenting framework like MooTools works on every browser:

var list_of_names = document.getElementsByTagName('input').map(
  function(element) { return element.getAttribute('name'); }
);

jQuery特定示例,适用于所有浏览器:

jQuery specific example, works on every browser:

var list_of_names = jQuery.map(jQuery('input'), function(element) { return jQuery(element).attr('name'); });

使用 .each 的其他答案是错误的;不是代码本身,但实现是次优的。

the other answers using .each are wrong; not the code itself, but the implementations are sub-optimal.

编辑:还有数组理解,但这纯粹依赖于语法,无法在本机缺少它的浏览器上进行模拟。这是您在Javascript中可以获得的最接近您发布的Python代码段的内容。

there's also Array comprehensions introduced in Javascript 1.7, but this is purely dependant on syntax and cannot be emulated on browsers that lack it natively. This is the closest thing you can get in Javascript to the Python snippet you posted.

这篇关于使Javascript做列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!