admin管理员组

文章数量:1305591

my problem is with appending a array into existing div as a text. I cant figure it out why its not working, so i have this code:

var raya = ui.item.value + ' ';  
$('#result').append(raya);
var tor = $("#result").text();

Above code is working, the value of raya (which is string) is appended correctly into #result
Problem es here, the value of array1 is not appended to #result2 and ideas why its not working?

var array1 = new Array();
array1 = tor.split( " " );
array1 = $.unique(array1);
$('#result2').append(array1);
return false;

(just to mention that everything is holded in 1 function, this cant be the reason, but just to know)

my problem is with appending a array into existing div as a text. I cant figure it out why its not working, so i have this code:

var raya = ui.item.value + ' ';  
$('#result').append(raya);
var tor = $("#result").text();

Above code is working, the value of raya (which is string) is appended correctly into #result
Problem es here, the value of array1 is not appended to #result2 and ideas why its not working?

var array1 = new Array();
array1 = tor.split( " " );
array1 = $.unique(array1);
$('#result2').append(array1);
return false;

(just to mention that everything is holded in 1 function, this cant be the reason, but just to know)

Share Improve this question edited Apr 23, 2011 at 8:44 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Apr 23, 2011 at 7:44 hayllonehayllone 1412 silver badges11 bronze badges 1
  • BTW you don't have to initialize arra1 with an empty array. You could even write e.g.: var new_tor = $.unique(tor.split(' ')).join(' '); – Felix Kling Commented Apr 23, 2011 at 8:03
Add a ment  | 

2 Answers 2

Reset to default 6

That's because append expects a string and you're sending it an array.

Two ways to solve it. Use either .toString() or .join()

$('#result2').append(array1.toString()); //inserts a ma separated list
$('#result2').append(array1.join(' '));  //inserts a string separated by what you pass as param

you can do something like this to explicitly convert array to string.

$('#result2').append(array1+'');

Here's a working example

http://jsfiddle/EsnLs/2/

本文标签: jquery or javascript array appending to div as a textStack Overflow