Reputation: 855
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?
Upvotes: 0
Views: 2224
Reputation: 1074168
When there is only one element in the string (no commas), the variable "nodes" does not become an array, but a regular variable.
A) Variables referring to arrays are regular variables. B) That's not how split
works. split
always 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 as data
returns a string, nodes
will be set to an array. Note, though, that data
does not always return a string, and so data("nodes").split(",")
may fail with the error that split
is not a function, because data
can return null
or an object as well as string
. If you know it will always be a string because of your application logic, that's fine, but if so nodes
will 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.
Upvotes: 5