1

Console debug shows me that array is ex. ["2"], but I need [2].

Why casting doesnt'work?

function filterElements(deals) {

    var result = deals,
        categories= $('#deals-categories').data('current_category');
        if (categories != undefined && categories.length > 0) {
            for (var i; i < categories.length; i++) {
                categories[i] = parseInt(categories[i]);
            }
            console.log(categories, 'cats');
                result = $.grep(result, function(e) {
                    return $.inArray(e.category_id, categories) != -1;
     });                
        }
    return result;
}

3 Answers 3

4

You need to initialize var i = 0 in the loop declaration.

Full code cleanup:

function filterElements(deals) {

    var result = deals,
        categories = $('#deals-categories').data('current_category');

        if (categories && categories.length) {
            for (var i=0; i<categories.length; i++) {
                categories[i] = parseInt(categories[i], 10);
            }
            console.log(categories, 'cats');
            result = $.grep(result, function(e) {
                return $.inArray(e.category_id, categories) !== -1;
            });                
        }

    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

The only weirdness I see now is using $.inArray() inside of $.grep().
0

use categories[i] * 1 to cast

parseInt works in a bit unexpected way sometimes :)

parseInt("010") will return 8 in some browsers, and 10 in others: http://www.w3schools.com/jsref/jsref_parseInt.asp

5 Comments

I think Matt Ball explains the issue, while parseInt is still not recommended when dealing with strings which are for sure ints.
@Michael why not? Ohhh, w3schools... /facepalm. This is why JSLint recommends that you always specify the radix in parseInt calls (until ECMAScript 5). A much better resource than w3schools: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
yeah, radix solves the issue, but requires too much letters :)
The better alternatives to parseInt() are Number or unary +, not *1.
0

Are you sure? This is an example similar to yours:

var strings = ["1", "2", "3"];
var valueAsInt = 0;

for(var i = 0; i < strings.length; i++){
   valueAsInt = parseInt(strings[i]);
   if(typeof(valueAsInt) == 'number'){
      alert('Is an integer');
   }
}

The message 'Is an integer' is shown three times. I think in your code the parser works, but maybe later, the value is converted to string by comparing with other string or, maybe some concatenation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.