[英]How can i check if two numbers start with the same digits Javascript
我需要检查两个数字是否以相同的数字开头,例如startsWith,但对于数字,
喜欢,
let a = 567
let b = 5
a.startsWith(b) should return true, but it is returning not a function.
a
转换为String
,因为在Strings
上可以使用startsWith
方法。 注意:您可以显式选择将b
转换为String
,但 JavaScript 会隐式执行此操作。
const a = 567, b = 5; console.log(String(a).startsWith(b));
将其转换为字符串。
a.toString().startsWith(6)
您当前的变量是一个数字,它没有 startsWith 方法。 startsWith 方法适用于字符串。 所以你需要这种转换。
您可以先尝试将数字转换为字符串:
let a = 567; let b = 5; console.log(a.toString().startsWith(b.toString()))
String
和toString()
的两种替代解决方案,只是为了彻底:
let a = 567, b = 5; console.log(`${a}`.startsWith(b)); console.log(('' + a).startsWith(b));
为了完整起见,您可以使用数学进行比较。 但这有点涉及。
2.75
,其中您只需要2
。 虽然 log 10 5 是0.70
,但您需要0
。2 - 0 = 0
Math.floor(567 / 10 ** 2)
给我们5
。
0
。 否则 10 的负幂会增加数字: 567 / 10 ** -2
是56700
,我们不想这样做。 function startsWithInteger(a, b) { //get which power of 10 each number is in const exponentA = Math.floor(Math.log10(a)); const exponentB = Math.floor(Math.log10(b)); //get magnitude to compare the two. Cap at 1 (10 ** 0) let comparativeMagnitude = 10 ** Math.max((exponentA - exponentB), 0); //get the "start of" of `a` with an intiger division //by the common power of 10 to get the same number of digits const startA = Math.floor(a / comparativeMagnitude); return startA === b; } console.log(startsWithInteger(567, 2)); //false console.log(startsWithInteger(267, 2)); //true console.log(startsWithInteger(567, 50)); //false console.log(startsWithInteger(567, 56)); //true console.log(startsWithInteger(567, 5670)); //false console.log(startsWithInteger(567, 567)); //true
尽管如此,作为字符串进行比较要方便得多,因为您不必执行所有这些操作或处理由此产生的不同情况。 例如,这保证仅适用于整数,传入带有小数部分的数字可能会给出错误的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.