所以希望你们现在已经明白了一个模式。我们可以设计一个数学公式来为我们做这个计算,而不是仅仅使用字符串。为了连接任意两个数 a 和 b 我们需要取 a 和10的乘积乘以长度 b 再加上 b。
那么我们如何得到数字 b 的长度呢?我们可以把 b 变成一个字符串然后得到它的长度属性。
a * Math.pow(10, new String(b).length) + b;
但是一定有更好的方法来做到这一点,没有附加条件,对不对? 是的,有。
对于任意两个以 B 为基数的数 a 和 b。我们将 a 乘以基数 B 乘以长度 b 的幂(使用 b 的对数基数,然后对它进行加法,得到最接近的整数,然后再加1) ,然后加上 b。
现在我们的代码是这样的:
a * Math.pow(10, Math.floor(Math.log10(b)) + 1) + b;
但是等等,如果我想在基数2或基数8做这个呢?我该怎么做?我们不能使用我们刚刚创建的公式,除了基数10以外的任何其他基数。JavaScript Math 对象已经有针对基数10和2的内置函数(只有 Math.log) ,但是我们如何获得针对其他基数的日志函数呢?我们把 b 的 log 除以基的 log。Math.log(b) / Math.log(base).
现在我们有了完整的基于数学的代码来连接两个数字:
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
如果你知道你只需要做10进制的数学运算,那么你可以加一个 base is unDefinition 的检查,然后设置 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
为了方便起见,我使用原型将函数添加到 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
// 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