Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat JS not working

var myjson = '{"name": "cluster","children": [';

for (var i = 0; i < unique.length; i++)
{
    var uniquepart = '{"' + unique[i] + '"';
    myjson.concat(uniquepart); 
    var sizepart = ', "size:"';
    myjson.concat(sizepart);
    var countpart = count[i] + '';
    myjson.concat(countpart);
    if (i == unique.length) {
        myjson.concat(" },");
    }
    else {
        myjson.concat(" }");
    }
} 

var ending = "]}";
myjson.concat(ending);

console.log(myjson);

Does anyone know why this string doesn't concat properly and I still end up with the original value?

like image 233
user1840255 Avatar asked Feb 27 '13 20:02

user1840255


People also ask

How does concat work in Javascript?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do you concatenate an element in Javascript?

The concat() method joins two or more strings. The concat() method does not change the existing strings. The concat() method returns a new string.

Can you concatenate arrays in Javascript?

concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Does concat mutate Java?

a String is immutable, meaning you cannot change a String in Java. concat() returns a new, concatenated, string.


2 Answers

The concat() method is used to join two or more strings.

Definition and Usage
This method does not change the existing strings, but returns a new string containing the text of the joined strings.
Ref: http://www.w3schools.com/jsref/jsref_concat_string.asp

For example:

myjson = myjson.concat(uniquepart); 

OR

myjson += uniquepart; 
like image 164
Derek Avatar answered Oct 03 '22 02:10

Derek


A javascript string is immutable so concat can only return a new value, not change the initial one. If you want to append to a string you have as variable, simply use

myjson += "some addition";
like image 35
Denys Séguret Avatar answered Oct 03 '22 02:10

Denys Séguret