返回选定元素属性的自定义jQuery选择器,如LINQ

Bey*_*ygi 3 javascript linq performance jquery css-selectors

问题

我需要查询作为对象数组返回的每个项目的一些属性

我们现在做了什么

$(' selector ').每个(创建文本数组或任何内容);

怎么了?

为什么我们要为每个要求迭代元素?

这与LINQ中的内容相同

IQueryable<Book>;
books.Select(b=> b.Text).ToArray();
// or another sample
books.Select(b=> new { b.Text , b.ISBN}).ToArray();
Run Code Online (Sandbox Code Playgroud)

我们/我需要什么?

选择指定的元素属性作为对象数组而不重复元素 - 称为延迟枚举的东西

可能吗?

我想是的,因为现在我有一些想法.

I already know about 'map' and 'each' methods, beware that both of them will reiterate over selector items.So yes map will results what i want, but not exactly. Also note that even C# that have more better performance than java-script is using this method that i'm asking for, So this is a requirement for all web-developers not just me and that's exactly why i'm sharing the problem here to be solved.

研究结果

使用jQuery对元素进行迭代是不可避免的,因为jQuery本身并没有找到使用循环文档元素的元素,直到示例伪类为止,因此为了实现jQuery基础结构的延迟枚举,我们必须强制jQuery迭代项目,这使得它变慢.

我使用名为'select'的伪类实现了延迟枚举,并传入.net就像lambda表达式一样.处理选择非常好,就像.net一样,但结果比map慢,每个jQuery方法高达50%.最后答案是jQuery map方法.

Fré*_*idi 5

您可能正在寻找map()方法:

var books_text = $(".book").map(function() {
    return $(this).text();
}).get();

var books_info = $(".book").map(function() {
    var $this = $(this);
    return {
        text: $this.text(),
        isbn: $this.attr("isbn")  // If stored in an attribute.
    };
}).get();
Run Code Online (Sandbox Code Playgroud)

  • 也许Beygi正在寻找一种延迟的枚举机制?如果我们使用javascript将数组映射到一个新数组,目标是对新数组中的元素执行某些操作,我们必须迭代两次元素,一次用于映射,一次用于执行该操作.使用延迟枚举机制,我们只需要迭代一次 - 在访问每个元素时将调用映射函数.这很容易在C#中完成.不知道在javascript中执行此操作的最佳方法虽然... (2认同)