Javascript jquery选择器与vanilla JS选择器,其中.length返回不同的结果

Javascript jquery选择器与vanilla JS选择器,其中.length返回不同的结果,javascript,jquery,Javascript,Jquery,给定以下HTML页面摘要 <form> <select id="select"> <option></option> <option></option> <option></option> </select> </form> 一个console.log()的结果使用$(“#选择”).length返回1和docu

给定以下HTML页面摘要

<form>
    <select id="select">
    <option></option>
    <option></option>
    <option></option>           
    </select>
</form>

一个
console.log()的结果
使用
$(“#选择”).length
返回1和
document.getElementById(“选择”).length
返回3。有人知道为什么会这样吗?我希望使用返回的值运行一个循环,但我不明白为什么它会有所不同。他们不是都应该回来吗?谢谢

$(…)
返回一个jQuery对象,它是一个类似数组的对象,包含零个或多个元素。
length
返回对象中的元素数

document.getElementById()
返回单个DOM对象,不在任何数组中(与getElementsByCassName等复数版本相反)。
巧合的是,
元素有一个
length
属性,它返回
中的项数

这就是您看到的。

对于jquery案例,使用:
$(“#选择”).get(0).length

这将为您提供jquery对象数组列表中的第一个也是唯一一个select DOM元素。这将是使用
document.getElementById(“select”)
调用得到的相同DOM元素


更新:要回答注释,select DOM元素的.length调用将返回select elements选项列表中的选项数。jquery列表上的.length返回与提供的选择器匹配的元素数
$(“#选择”).get(0)
document.getElementById(“选择”)
是同一个对象
$(“#select”)
不是同一个对象——它是jquery对象的列表,而不是DOM元素。

感谢您的快速回复!那么,我如何使用jQuery获得3的值呢?
$(“#选择选项”)。length
将为您提供3,或者检查David Fleeman的答案。请注意,
$(“#选择”).get(0)
仅当确实存在匹配元素时,才会返回与
document.getElementById(“选择”)
相同的值。(否则,第一个返回
undefined
,而第二个返回
null
)是的,我的答案假设问题中提供的代码中存在元素。