How can I join an array of numbers into 1 concaten

2020-03-01 18:32发布

问题:

How do I join this array to give me expected output in as few steps as possible?

var x = [31,31,3,1]
//expected output: x = 313131;

回答1:

Use array join method.Join joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.

var  x = [31,31,3,1].join("");


回答2:

I can't think of anything other than

+Function.call.apply(String.prototype.concat, x)

or, if you insist

+''.concat.apply('', x)

In ES6:

+''.concat(...x)

Using reduce:

+x.reduce((a, b) => a + b, '');

Or if you prefer

x.reduce(Function.call.bind(String.prototype.concat), '')

Another idea is to manipulate the array as a string, always a good approach.

+String.prototype.replace.call(x, /,/g, '')

There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.



回答3:

Javascript join() will give you the expected output as string. If you want it as a number, do this:

var x = [31,31,3,1];
var xAsString = x.join(''); // Results in a string
var xAsNumber = Number(x.join('')); // Results in a number, you can also use +(x.join(''))


回答4:

Your question asks for a number, most of the answers above are going to give you a string. You want something like this.

const number = Number([31,31,3,1].join(""));



回答5:

Try join() as follows

var x = [31,31,3,1]
var y = x.join('');
alert(y);



回答6:

Try below.

var x = [31,31,3,1]
var teststring = x.join("");


回答7:

This will work

var x = [31,31,3,1];
var result = x.join("");