数字数组作为字符串到简单 int 转换问题
控制台调试显示数组是 ex。 [“2”],但我需要[2]。
为什么铸造不起作用?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在循环声明中初始化
var i = 0
。完整代码清理:
You need to initialize
var i = 0
in the loop declaration.Full code cleanup:
使用
categories[i] * 1
转换parseInt
有时会以一种意想不到的方式工作:)parseInt("010")
将返回 8一些浏览器,其他浏览器有 10 个:http://www.w3schools.com/jsref/jsref_parseInt.aspuse
categories[i] * 1
to castparseInt
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:
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.