2

I have below line of code in JavaScript which iterate through object's item using for..in function but problem is that it giving me always index value & other values instead of object's item.

for (imgElem in $('.icon-bookmark-checked')){                       
                        console.log(imgElem)
                    }

Above line of code giving me output like below.

0
1
2
3
4
length
prevObject
context
selector
jquery
constructor
toArray
get
pushStack
each
map
slice
first
last
eq
end
push
sort
splice
extend
find
filter
not
is
init
has
closest
index
add
addBack
parent
parents
parentsUntil
next
prev
nextAll
prevAll
nextUntil
prevUntil
siblings
children
contents
ready
data
removeData
queue
dequeue
clearQueue
promise
on
one
off
trigger
triggerHandler
text
append
prepend
before
after
remove
empty
clone
html
replaceWith
detach
domManip
appendTo
prependTo
insertBefore
insertAfter
replaceAll
css
show
hide
toggle
fadeTo
animate
stop
finish
slideDown
slideUp
slideToggle
fadeIn
fadeOut
fadeToggle
delay
val
attr
removeAttr
prop
removeProp
addClass
removeClass
toggleClass
hasClass
blur
focus
focusin
focusout
load
resize
scroll
unload
click
dblclick
mousedown
mouseup
mousemove
mouseover
mouseout
mouseenter
mouseleave
change
select
submit
keydown
keypress
keyup
error
contextmenu
hover
bind
unbind
...

Does have any idea what wrong I am doing here ?

I have tried lot but not able to succeed.

How to achieve this task with for..in loop ?

Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
Moon
  • 4,014
  • 3
  • 30
  • 66
  • 2
    `for..in` iterates over keys, not values. Use `.each` instead – CertainPerformance Dec 03 '19 at 06:51
  • Because that's what it's defined to do. Maybe you wanted `for..of` as in `for (const imgElem of $('.icon-bookmark-checked')){ console.log(imgElem) }` – gman Dec 03 '19 at 06:52
  • `for (imgElem of $('.icon-bookmark-checked')).toArray()) { ... }` works, as does `$('.icon-bookmark-checked')).each((i, imgElem) => { ... })`. – Amadan Dec 03 '19 at 06:57
  • 1
    [jQuery Learning Center -> Iterating over jQuery and non-jQuery Objects](https://learn.jquery.com/using-jquery-core/iterating/) – Andreas Dec 03 '19 at 06:58
  • @gman _"You can stop the loop from within the callback function by returning `false`"_ ([Source](https://api.jquery.com/each/)) – Andreas Dec 03 '19 at 06:59
  • why do you need `toArray`. for of seems to work without it. – gman Dec 03 '19 at 07:01
  • note: the question asked is "Why javascript for..in function iterating through index rather than item in object?" with a secondary question of "How to achieve this task with for..in loop ?" The question it is not "how do I iterate over the results of a jquery query" though I'm sure that is useful to the asker. – gman Dec 03 '19 at 07:05
  • In that case, the answer would be simply to use `$('.icon-bookmark-checked')[imgElem]`. – Mr Lister Dec 03 '19 at 07:11

0 Answers0