最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - push array value in variable using java script - Stack Overflow

programmeradmin8浏览0评论

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.

Share Improve this question edited May 14, 2013 at 15:11 Anvesh 10111 bronze badges asked May 14, 2013 at 15:03 Jack PhpJack Php 5772 gold badges7 silver badges26 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 5

You 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)

发布评论

评论列表(0)

  1. 暂无评论