Moritz Friedrich
Moritz Friedrich

Reputation: 1481

Simple math addition in JS giving wrong result

I have this strange problem I can't get my head around. I try to find the highest number in a list of elements which have a data-index attribute for their respective number. But when iterating over them, JS insists that 9 < 10 is false.
See this fiddle: http://jsfiddle.net/1ztbxbjx/

What I'm doing wrong?

I can't use

for (i = 0; i < $('div[data-index]'; i++))

Sometimes there will be numbers out of order in the list (eg. 1,2,3,4,5,25,31).

Upvotes: 0

Views: 879

Answers (3)

Omkar Kulkarni
Omkar Kulkarni

Reputation: 824

Use this

if (indexCount < parseInt(current)) {

instead of

if (indexCount < current) {

Upvotes: 1

Sachin Thapa
Sachin Thapa

Reputation: 3709

Parse retreived id to Number and it should work fine, try this:

var current = Number($(this).attr('id'));

Tested in JSFiddle, its working fine after this one line change.

Cheers !

Upvotes: 1

depperm
depperm

Reputation: 10746

You need to parse the id, otherwise you're comparing strings. Here is an example using parseInt()

Upvotes: 2

Related Questions