javascript 如何将一组数字连接成 1 个串联数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30229522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I join an array of numbers into 1 concatenated number?
提问by Matthew Harwood
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;
采纳答案by Gilsha
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.
使用数组join
方法。Join
将数组的元素连接成一个字符串,并返回该字符串。默认分隔符是逗号 (,)。这里的分隔符应该是一个空字符串。
var x = [31,31,3,1].join("");
回答by Gilsha
I can't think of anything other than
我想不出别的了
+Function.call.apply(String.prototype.concat, x)
or, if you insist
或者,如果你坚持
+''.concat.apply('', x)
In ES6:
在 ES6 中:
+''.concat(...x)
Using reduce
:
使用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.
可能还有其他方式。也许谷歌搜索“join array javascript”会出现一些连接数组元素的晦涩函数。
回答by Zee
Javascript join()will give you the expected output as string
. If you want it as a number
, do this:
Javascript join()将为您提供预期的输出string
。如果你想要它作为number
,请执行以下操作:
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(''))
回答by iPzard
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(""));
const number = Number([31,31,3,1].join(""));
回答by Shijin TR
Try join() as follows
尝试 join() 如下
var x = [31,31,3,1]
var y = x.join('');
alert(y);
回答by RE350
Try below.
下面试试。
var x = [31,31,3,1]
var teststring = x.join("");
回答by Mahesh Jayachandran
This will work
这将工作
var x = [31,31,3,1];
var result = x.join("");