Sometimes when using JQuery's for in and each loops, the attributes related to elements will be looped out. What are these attributes used for? Can you explain it in a simple way? Why does it not appear when using a for loop?
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/jquery-2.1.4.min.js">
</script>
</head>
<body>
<a href="1">A</a>
<a href="2">B</a>
<a href="3">C</a>
</body>
<script type="text/javascript">
$(function(){
$("a").each(function(){
console.log($(this));
})
})
</script>
</html>
Console screenshot
Because $("a") returns a jQuery object, and it is not an array, but an object. You can judge it through Array.isArray. The extra attributes you mentioned are used To store some things that jQuery needs to use internally. If you want a clean array, you can use $('a').get();
The for loop does not cycle out the redundant attributes. That is because of the problem of your loop. What you pass is [0], [1] and so on. And the redundant attributes you mentioned are not numbers, so naturally they will not It's been recycled.
$("a")
itself will get a pseudo array, for whicheach()
loops in this array, and each loop processes a jQuery-encapsulated"a"
object, which is listed Properties are properties of the jQuery object of this"a"
. If there is no$(this)
, directly usethis
to print out a DOM object and its attributes. Usingfor
should have the same effect.