开发者

Array of digit as string to simple int conversion problem

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] = parse开发者_C百科Int(categories[i]);
            }
            console.log(categories, 'cats');
                result = $.grep(result, function(e) {
                    return $.inArray(e.category_id, categories) != -1;
     });                
        }
    return result;
}


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;
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜