4

<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?

8
  • 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. Commented Dec 27, 2010 at 16:38
  • Thanks! Did the best I could with the amount of information that was given to me :-) Commented Dec 27, 2010 at 16:43
  • both changelog and patrick dw work, which is better / faster? Commented Dec 27, 2010 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. Commented Dec 27, 2010 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. Commented Dec 27, 2010 at 17:06

2 Answers 2

9

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];
}
Sign up to request clarification or add additional context in comments.

2 Comments

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: 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.
6
var columns = $('#dynamicTable').attr('columns'),
    attributeIds = $.map(columns.split(','), function(val, idx) { return parseInt(val, 10) });

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.