Javascript 如何将 jQuery .find() 函数的结果转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7513292/
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-24 02:33:44  来源:igfitidea点击:

How to convert the result of jQuery .find() function to an array?

javascriptjqueryjquery-selectors

提问by Leem

What does jQuery .find()method return? a objectOR a array listof objects?

jQuery.find()方法返回什么?一个对象数组列表的对象?

If it returns an object which contain all the matched elements. How to convert this object to an array?

如果它返回一个包含所有匹配元素的对象。如何将此对象转换为数组?

If it returns a array of elements, why $(xml).find("DATE").sort(mySortFunc);does not work, it seems the jQuery .find()returns an object which can not apply Javascript sort()method which is supposed to be applied on array.

如果它返回一个元素数组,为什么$(xml).find("DATE").sort(mySortFunc);不起作用,似乎 jQuery.find()返回一个对象,该对象不能应用sort()应该应用于数组的Javascript方法。

Generally, I need to sort the objects find by $(xml).find("DATE"), but when I use sort function, it raised an error that the object can not be resolved.

通常,我需要对 find by 的对象进行排序$(xml).find("DATE"),但是当我使用 sort 函数时,它引发了对象无法解析的错误。

回答by Matt

The majority of jQuery methods returns a jQuery object, which can be accessed like it is an array (e.g. it has a .lengthattribute, elements can be accessed using the square bracket notation ([0]), and it supports somearray methods (slice())).

大多数 jQuery 方法返回一个 jQuery 对象,可以像访问数组一样访问它(例如,它有一个.length属性,可以使用方括号符号 ( [0])访问元素,并且它支持一些数组方法 ( slice()))。

jQuery has a method called toArray()which can be used to convert the jQuery object to a real array.

jQuery 有一个被调用的方法toArray(),可用于将 jQuery 对象转换为真正的数组。

You can also use get()with no arguments to achieve the same effect (and save you a few key presses).

您也可以使用get()不带参数来实现相同的效果(并节省您的几次按键操作)。

In future, you can checkout the jQuery API, and the return type for all jQuery methods is listed in the relevant documentation (e.g. for find(), the return type is "jQuery")

以后可以查看 jQuery API,所有 jQuery 方法的返回类型都列在相关文档中(例如 for find(),返回类型为“jQuery”)

回答by Dennis

If you call .get()on a jQuery object without a parameter, it will return a regular array of DOM elements.

如果您.get()在没有参数的情况下调用jQuery 对象,它将返回一个常规的 DOM 元素数组。

回答by Martin Jespersen

jQuery already acts like an array, and thus you can apply array like functionality to it.

jQuery 已经像一个数组一样工作,因此您可以将类似数组的功能应用到它。

Try to change

尝试改变

$(xml).find("DATE").sort(mySortFunc);

with

Array.prototype.sort.apply($(xml).find("DATE"), mySortFunc);

and you should get what you need

你应该得到你需要的