I have one string, i want to split this and push it in variable.
i am try to push array value in variable result
this is what i tried.
var region = "Rajkot,Jamnagar,Surat";
var result;
var array = region.split(',');
for (var i=0; i<array.length; i++ )
{
alert(array[i]);
result.push(array[i]);
}
but its returning error result.push is not a function.
how to push value on variable
and i am trying to alert this result variable.
please solve my query.
thanks.
I have one string, i want to split this and push it in variable.
i am try to push array value in variable result
this is what i tried.
var region = "Rajkot,Jamnagar,Surat";
var result;
var array = region.split(',');
for (var i=0; i<array.length; i++ )
{
alert(array[i]);
result.push(array[i]);
}
but its returning error result.push is not a function.
how to push value on variable
and i am trying to alert this result variable.
please solve my query.
thanks.
-
var region = "Rajkot,Jamnagar,Surat"; var result = region.split(',');
should be enough. – Utopik Commented May 14, 2013 at 15:10 -
Quick question - why not just do
result = region.split(",");
? – Ian Commented May 14, 2013 at 15:10
4 Answers
Reset to default 5You should initialize the result
variable as
var result = [];
So your final code would be:
var region = "Rajkot,Jamnagar,Surat";
var result = [];
var array = region.split(',');
for (var i=0; i<array.length; i++ ){
alert(array[i]);
result.push(array[i]);
}
But split()
already returns an array, so your for
might be unnecessary, unless you wish to do business logic with the elements of the array before adding them to the results.
i think you need to initialize result as an array
ie var result = [];
Why are you pushing the array? split
returns an array.
var region = "Rajkot,Jamnagar,Surat";
var result = region.split(','); // This is already an array
for (var i in result) {
alert(result[i]);
}
See DEMO.
In order to use the functions in the Array
prototype, you'll need to actually have an array. Right now, you have a result
variable which is undefined (and cannot therefore support push
).
In order for it to work, you need to make sure that the type of your variable is actually an array. This can be done like this:
var result = [];
(always remember to initialize your arrays if you are not using a function to do so)