I have a string that has data separated by a pipe character (|).
Example
var somestring = "data1|data2|data3";
var separated = somestring.split("|");
I know how to use the split() to separate each data.
However, I don’t know how many pipes there will be in the resulting Array.
In jQuery or JavaScript, how do I loop over the array returned?
You basically just need to iterate over the resulting
Array.jQuery
$.eachloopThis method is easy to work with, and benefits in the variables used being encapsulated.
jsFiddle.
Of course, jQuery is JavaScript so any of the below methods will also work.
JavaScript
forloopThis is the recommended way.
jsFiddle.
You’ll notice too the
lengthproperty is cached so it is not looked up on each iteration. Some browsers already optimise for this, however IE appears to still benefit from it cached. It only takes 5 seconds to do, so you may as well keep IE users happy too.You may want to define
iandchunkoutside of theforloop, because JavaScript has no block scope (unless you’re usinglet), and those variables will exist before (declaration hoisted) and after (no block scope).for ( in )loopThis loop is generally not recommended, as it should be used for iterating over object properties only, not array like member properties.
jsFiddle.
This loop will loop over all properties up the prototype chain, so
hasOwnProperty()must be used. For this reason it is not recommended for arrays.for ( of )loopThis loop is standardized in ECMA 6 and is able to loop over
NodeLists and iterators.jsFiddle
forEach()methodThis method is an addition to the ECMA-262 standard. It’s not available in IE8, but it can be shimmed relatively easily.
jsFiddle.
Other specialised methods
If you’re looking to iterate for a specific goal, it may be useful to use a specialised iterator. Keep in mind these also don’t have the best browser support.
filtermethodCreates a mew array of the elements which the associated callback returned truthy for.
reducemethodCreates a new value based on reducing the elements of the array, from left to right.
See also the
reduceRightmethod.mapmethodCreates a new array, replacing each element with the returned value of the associated callback.
everymethodReturns a boolean value of which is the result of every element in the array passing the test. This method short circuits, i.e. it returns whenever one element’s callback doesn’t return truthy.
somemethodReturns a boolean value of which is the result of some element in the array passing the test. This method short circuits, i.e. it returns whenever one element’s callback passes the test.