[英]Better way to put numbers side by side. Javascript
I was wondering if there was a better approach to putting 2 numbers side by side without having to make them into a string.我想知道是否有更好的方法可以将两个数字并排放置,而不必将它们变成一个字符串。
For example:例如:
if i have '2' and '3' and I wanted to '23' you would just concat them.如果我有 '2' 和 '3' 而我想要 '23' 你会连接它们。 But what if they were the number data type.
但是如果它们是数字数据类型呢?
I was working with binaries and realized I don't actually know anyway to have我正在使用二进制文件并意识到我实际上并不知道有
0101, and 1010 and put them together to create 01011010 without turning them into strings. 0101 和 1010 并将它们放在一起创建 01011010 而不将它们变成字符串。
I know it's an odd question but I am just curious.我知道这是一个奇怪的问题,但我只是好奇。 Thanks again.
再次感谢。
Here's a method of doing it without string concatenation:这是一种无需字符串连接的方法:
var values = [2,3];//Also works with arbitrary length arrays, e.g. [1,2,3,4,5]
var result = 0;
for (var i = 0; i < values.length; ++i) {
var step = values[i] * (Math.pow(10, values.length - i) / 10);
result += step;
}
https://jsfiddle.net/ysd6exvw/ https://jsfiddle.net/ysd6exvw/
I've haven't benchmarked it for speed, and TBH I would suggest just using string concatenation instead of complicating the problem with this code.我还没有对它的速度进行基准测试,TBH 我建议只使用字符串连接而不是用这段代码使问题复杂化。
EDIT:编辑:
Added a benchmark:添加了一个基准:
https://jsfiddle.net/4ap82rgq/ https://jsfiddle.net/4ap82rgq/
This shows that the string concatenation is fastest, although I did get one result where the above code was faster.这表明字符串连接是最快的,尽管我确实得到了一个结果,上面的代码更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.