Madhan
Madhan

Reputation: 107

array indexof() not working for dynamic value

array indexof() not working for dynamic value.

If use like:

var arr ='1,2,3,4,';
del_row = arr.slice(0,-1);
del_array = del_row.split(',');
var a = del_array.indexOf('2');

It works, But I am using like:

for(var i='1';i<=rowcnt;i++) {
    var del_row = $('#hid_delrow').val();
    if(del_row != ''){
        del_row = del_row.slice(0,-1);
        del_array = del_row.split(',');
        del_length = del_array.length;
        var a = del_array.indexOf(i);
        //var a = $.inArray(i,del_array)
        if(a != '-1'){
            continue;
        }
    }
 }

Its not Working, I also try:

del_array.indexOf(parseInt(j, 10));

and

$.inArray(j,del_array);

all returns value as -1 . Help me.

Upvotes: 0

Views: 1426

Answers (2)

Harveer Singh Aulakh
Harveer Singh Aulakh

Reputation: 356

simple example of indexof() are:--

<script>
var arr = ['a', 'b', 'c', '123', 'xyz'];
console.log("Array index"+" "+arr.indexOf('b')); 
alert("Array index"+" "+arr.indexOf('b'));
</script>

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129832

The value of del_array is an array of strings.

indexOf will work when you pass a string - indexOf('2') - but not when you pass an int indexOf(i). The fact that you declare it as var i = '1' isn't enough to make it a string, because you then proceed to do integer operations on it (i++).

You need to either make your integer a string:

var a = del_array.indexOf(i.toString());

... or make del_array a list of integers:

del_array = del_array.map(function(x) { return parseInt(x); });
var a = del_array.indexOf(i);

Upvotes: 2

Related Questions