I have this code, that takes a string and splits it into an array:
nodes = $("#" + model_id + "-" + node_class + "--" + "title").data("nodes").split(",")
When there is only one element in the string (no commas), the variable “nodes” does not become an array, but a regular variable. So when I try to iterate over each element in “nodes”, nothing happens if the original string only contains one element. If it has several elements, everything is OK.
$.each(nodes, function (id, node_id) {
if ($("#" + model_id + "-" + node_class + "-" + node_id + "-" + "chkbx").is(":checked")) {
counter ++
}
})
I have tried to declare “nodes” as an array, but when I assign the splitted string, it’s all the same. Since I use a “split” to assign values I don’t think I can use “push” to append values to the array.
I have tried to put square brackets everywhere, I think, i.e. like this:
[nodes] = $("#" + model_id + "-" + node_class + "--" + "title").data("nodes").split(",")
… but that didn’t help.
Is there any solutions to this, except from checking if “nodes” is an array or not, and then write different code to handle both options?
A) Variables referring to arrays are regular variables. B) That’s not how
splitworks.splitalways returns an array. If the delimiter isn’t present in the string, the resulting array is one element in length. (Live proof) So as long asdatareturns a string,nodeswill be set to an array. Note, though, thatdatadoes not always return a string, and sodata("nodes").split(",")may fail with the error thatsplitis not a function, becausedatacan returnnullor an object as well asstring. If you know it will always be a string because of your application logic, that’s fine, but if sonodeswill always be an array, which is why I mention it.Re your comment below: Iteration works just fine on single-element arrays: http://jsbin.com/ehucop/2
I suspect you need to look at the JavaScript console in your browser, I bet you’ll find an error occurring which is preventing your iteration code from running at all.