Renegade605 Posted April 13, 2009 Share Posted April 13, 2009 So I have a function where you pass it an array of strings, or arrays. Eg: func([ "string1", [ "string2-1", "string2-2", "string2-3" ], "string3" ]); The idea is, to make things easier on the end-user, they don't have to put every string within an array. If all 3 indices of the array are the same, they just specify a string and the function will convert it to an array where all 3 values are the same.The way I was doing it was this: ('ops' is the array arg that is passed to it) for (var i = 0; i < ops.length; i++){ if (ops[i][0].length > 1) { ops[i] = ops[i] || [ ]; } else { ops[i] = [ ops[i] ] || [ ]; }} This was made under the assumption that retrieving the index of a string just returned the character at that position.This presents two problems: If the user wants to specify an array where the 0 index is a string of length 1 (ie. "a"), the code will think it's a regular string and not an array, messing up the script. (This is the one I didn't see coming.) IE doesn't seem to behave the same way as FF when dealing with a string like an array. Instead of returning the character at pos 0, it returns 0, thus giving the error "0.length" is not a function. Therefore, it seems to me like I need a better way of detecting string versus array. I've tried comparing the original (ops) and the var with the .toString() method. Code: if (ops[i] == ops[i].toString()) { ops[i] = [ ops[i] ] || [ ]; }else { ops[i] = ops[i] || [ ]; } According to tests I ran in Firebug's console: "string".toString() = "string"[ "array_1", "array_2" ].toString() = "array_1,array_2" So I thought this would work. However, logging (ops == ops.toString()) always returned true, whether ops was a string or an array.So now I'm stumped, does anyone else have some insight into this?Thanks, Link to comment Share on other sites More sharing options...
justsomeguy Posted April 13, 2009 Share Posted April 13, 2009 If you want to convert a string to an array, you can use string.split. If you want to refer to a specific character in a string, you can use string.charAt.To detect an array, one way is to check for a method that exists on arrays, like array.push or array.shift. If it's undefined, it's not an array. If obj.push is undefined, but obj.length is defined, it's probably a string, because both strings and arrays have a length property but only an array has a push method. You can use the typeof operator to check if something is undefined:if ((typeof obj.push) == "undefined") Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.