Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

<div id="dynamicTable" columns="26,40,41,21,71,39,23,19">

var columns = $('#dynamicTable').attr('columns');
var attributeIds = new Array();
attributeIds = columns.split(',');

This creates an array of strings, I need them to be ints. What's the best way to do this?

share|improve this question
1  
changelog answer is no doubt the most elegant possible, but depending on what you need to do with those integers maybe you can do it directly in the map function instead of storing the new array in separate variable. – Shadow Wizard Dec 27 '10 at 16:38
Thanks! Did the best I could with the amount of information that was given to me :-) – changelog Dec 27 '10 at 16:43
both changelog and patrick dw work, which is better / faster? – Mark Dec 27 '10 at 16:49
Both are equally good. Speed isn't an issue here, since it's so fast the difference would be negligible. My only concern in regards to $.parseJSON, as far as I know, is that if you don't include the json2.js library, some older browsers don't implement the native JSON parsing functionality, which has only been around since Dec 2009. – changelog Dec 27 '10 at 17:03
Nevermind the previous comment. jQuery creates a new function with a body of 'return ' + data, which is essentially the same as eval() when the browser can't do native JSON parsing. – changelog Dec 27 '10 at 17:06
show 3 more comments

2 Answers

up vote 7 down vote accepted

You could use $.parseJSON.

Example: http://jsfiddle.net/ULkXy/

var columns = $('#dynamicTable').attr('columns');
var attributeIds = $.parseJSON( '[' + columns + ']' );

Here's another way using a while loop with the unary + operator:

Example: http://jsfiddle.net/ULkXy/1/

var columns = $('#dynamicTable').attr('columns');
var attributeIds = columns.split(',');
var len = attributeIds.length;

while( len-- ) {
    attributeIds[len] = +attributeIds[len];
}
share|improve this answer
1  
Hey that's pretty slick and works. – Mark Dec 27 '10 at 16:45
Problem with that last solution is that it inverts the order of the ids. What if the ids need to be sent in a specific order? – changelog Dec 27 '10 at 18:51
@changelog: It doesn't invert the order. It just iterates through the array in reverse. If there are 10 items, index 9 is overwritten by a modified value of index 9. Then 8, 7, 6, etc.. If you click the example link I provided, you'll see that the result in the alert() has the same order as that in the columns attribute. – user113716 Dec 27 '10 at 20:15
var columns = $('#dynamicTable').attr('columns'),
    attributeIds = $.map(columns.split(','), function(val, idx) { return parseInt(val, 10) });
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.