简体   繁体   中英

How to split a string into an array in jQuery when there is only one element in the string?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM