简体   繁体   English

如何在javascript中连接两个数字?

[英]How to concatenate two numbers in javascript?

我希望5 + 6之类的东西返回"56"而不是11

Use "" + 5 + 6 to force it to strings.使用"" + 5 + 6将其强制为字符串。 This works with numerical variables too:这也适用于数值变量:

 var a = 5; var b = 6; console.log("" + a + b);

You can now make use of ES6 template literals.您现在可以使用ES6模板文字。

const numbersAsString = `${5}${6}`;
console.log(numbersAsString); // Outputs 56

Or, if you have variables:或者,如果您有变量:

const someNumber = 5;
const someOtherNumber = 6;
const numbersAsString = `${someNumber}${someOtherNumber}`;

console.log(numbersAsString); // Outputs 56

Personally I find the new syntax much clearer, albeit slightly more verbose.就我个人而言,我发现新语法更清晰,尽管稍微冗长一些。

var value = "" + 5 + 6;
alert(value);

只需使用:

5 + "" + 6

I know this is an old post and has been answered many times.我知道这是一个旧帖子,并且已经回答了很多次。 I too was wondering if JavaScript had a function that would do this.我也想知道 JavaScript 是否有一个可以做到这一点的函数。 I was doing some math programming and needed to concatenate two numbers.我正在做一些数学编程,需要连接两个数字。

So the what if I needed to combine two numbers 17 and 29. Sure I can turn them into strings and concatenate them then turn the new string back into a number.那么如果我需要将两个数字 17 和 29 组合起来怎么办。当然,我可以将它们转换为字符串并将它们连接起来,然后将新字符串转换回一个数字。 That seems to work pretty well and I can go on with my code, but lets take a look here and try to figure out what is really happening here.这似乎工作得很好,我可以继续我的代码,但让我们看看这里并尝试弄清楚这里到底发生了什么。

What are we doing to these two numbers, how do we take 17 and 29 and turn it into one thousand seven hundred and twenty-nine?我们对这两个数字做了什么,我们如何将 17 和 29 变成一千七百二十九? Well we can multiply 17 by 100 then add 29. And how about 172 and 293 to get one hundred seventy-two thousand two hundred and ninety-three?好吧,我们可以将 17 乘以 100 然后再加上 29。那么 172 和 293 得到 172293 怎么样? Multiply 172 by 1000 and add 293. But what about only 2 and 9?将 172 乘以 1000 再加上 293。但是只有 2 和 9 呢? Multiply 2 by 10 then add 9 to get 29.将 2 乘以 10,然后加 9 得到 29。

So hopefully by now a pattern should be apparent to you.所以希望到现在你应该很清楚一个模式。 We can devise a math formula to do this calculation for us rather than just using strings.我们可以设计一个数学公式来为我们做这个计算,而不仅仅是使用字符串。 To concatenate any two numbers, a and b, we need to take the product of a and 10 to the power of length b then add b.要连接任意两个数字 a 和 b,我们需要将 a 和 10 的乘积乘以长度 b 的幂,然后加上 b。

So how do we get the length of number b?那么我们如何得到数字b的长度呢? Well, we could turn b into a string and get the length property of it.好吧,我们可以把 b 变成一个字符串并得到它的长度属性。

    a * Math.pow(10, new String(b).length) + b;

But there has to be a better way to do this without strings, right?但是必须有更好的方法来做到这一点,而不需要字符串,对吧? Yes there is.就在这里。

在此处输入图像描述

For any two numbers, a and b, with any base B. We are going to multiply a by base B to the power of length b (using log base of b then flooring it to get the nearest whole number then adding 1 to it) then adding b.对于任意两个数字,a 和 b,任何底数 B。我们将 a 乘以底数 B 到长度 b 的幂(使用 b 的对数底数,然后将其取底以得到最接近的整数,然后将其加 1)然后添加 b。

So now our code looks like this:所以现在我们的代码如下所示:

    a * Math.pow(10, Math.floor(Math.log10(b)) + 1) + b;

But wait, what if I wanted to do this in base 2 or base 8?但是等一下,如果我想在 base 2 或 base 8 中执行此操作怎么办? How can I do that?我怎样才能做到这一点? We can't use our formula that we just created with any other base but base 10. The JavaScript Math object already has built-in functions for base 10 and 2 (just Math.log), but how do we get log functions for any other base?我们不能使用我们刚刚创建的任何其他基数但基数为 10 的公式。JavaScript Math 对象已经具有基数为 10 和 2 的内置函数(仅 Math.log),但是我们如何获得任何其他基数的日志函数其他基地? We divide the log of b by the log of base.我们将 b 的对数除以基数的对数。 Math.log(b) / Math.log(base).

So now we have our fully functioning math based code for concatenating two numbers:所以现在我们有了用于连接两个数字的功能齐全的基于数学的代码:

    function concatenate(a, b, base) {
        return a * Math.pow(base, Math.floor(Math.log(b) / Math.log(base)) + 1) + b;
    }
    var a = 17, var b = 29;
    var concatenatedNumber = concatenate(a, b, 10);
    // concatenatedNumber = 1729

If you knew you were only going to be doing base 10 math, you could add a check for base is undefined then set base = 10:如果你知道你只会做以 10 为底的数学,你可以添加一个检查 base is undefined 然后设置 base = 10:

    function concatenate(a, b, base) {
        if(typeof base == 'undefined') {
            base = 10;
        }
        return a * Math.pow(base, Math.floor(Math.log(b) / Math.log(base)) + 1) + b;
    }

    var a = 17, b = 29;
    var newNumber = concatenate(a, b); // notice I did not use the base argument
    // newNumber = 1729

To make it easier for me, I used the prototype to add the function to the Number object:为了方便我,我使用原型将函数添加到 Number 对象:

    Number.prototype.concatenate = function(b, base) {
        if(typeof base == 'undefined') {
                base = 10;
        }
        return this * Math.pow(base, Math.floor(Math.log(b) / Math.log(base)) + 1) + b;
    };
    var a = 17;
    var newNumber = a.concatenate(29);
    // newNumber = 1729

简单的回答:

5 + '' + 6;
var output = 5 + '' + 6;

Use利用

var value = "" + 5 + 6;

to force it to strings.强制它串起来。

You can also use toString function to convert it to string and concatenate.您还可以使用toString函数将其转换为字符串并连接。

var a = 5;
var b = 6;
var value = a.toString() + b.toString();

另一种可能是:

var concat = String(5) + String(6);
// enter code here
var a = 9821099923;
var b = 91;
alert ("" + b + a); 
// after concating , result is 919821099923 but its is now converted into string  

console.log(Number.isInteger("" + b + a))  // false

// you have to do something like this

var c= parseInt("" + b + a)
console.log(c); // 919821099923
console.log(Number.isInteger(c)) // true

这是执行此操作的简单方法

var value = 5 + "" + 6;

I converted back to number like this:我转换回这样的数字:

const timeNow = '' + 12 + 45;
const openTime = parseInt(timeNow, 10);

outputs输出

1245

I'd prefer the concat way :我更喜欢concat方式:

const numVar1 = 5;
const numVar2 = 6;
const value = "".concat(numVar1, numVar2);
// or directly with values
const value2 = "".concat(5, 6);

You can also use an array which can help in some use cases :您还可以使用在某些用例中可以提供帮助的数组:

const value3 = [5, 6, numVar1].join('');

To add to all answers above I want the share the background logic:要添加到上面的所有答案,我希望分享背景逻辑:

Plus is an addition operator that is also used for concatenation of strings. Plus是一个加法运算符,也用于字符串的连接。 When we want to concatenate numbers.当我们想要连接数字时。 It should be the understanding that we want to concatenate the strings, as the concatenation of numbers doesn't make valid use cases to me.应该理解我们想要连接字符串,因为数字的连接对我来说不是有效的用例。

We can achieve it in multiple ways,我们可以通过多种方式实现它,

Through type conversion通过类型转换

let a = 5;
a.toString()+5 // Output 55 type "string"

This will also work and doing type conversion in the background,这也将在后台工作并进行类型转换,

5 +""+ 5 // Output 55 type "string"

If you are determined to concatenate two string and type of output should be int, parseInt() works here如果您确定连接两个字符串并且输出类型应该是 int,则 parseInt() 在这里工作

parseInt(5 +""+ 5)  //Output 55 Type "number"

You can return a number by using this trick:您可以使用此技巧返回一个数字
not recommended不建议

[a] + b - 0

Example :例子 :

let output = [5] + 6 - 0;
console.log(output); // 56
console.log(typeof output); // number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM