在 JavaScript 中获取数字的最后 2 位数字
要获取数字的最后 2 位数字:
- 将数字转换为字符串。
-
对字符串调用
slice()
方法,将 -2 作为参数传递给它。 -
slice()
方法将返回字符串中的最后 2 个字符。 - 将字符串转换回数字以获得最后 2 位数字。
const num = 2468;
const last2Str = String(num).slice(-2); // 👉️ '68'
const last2Num = Number(last2Str); // 👉️ 68
第一步是使用 String
对象将数字转换为字符串,因此我们可以使用 String.slice 方法。
JavaScript 索引是从零开始的。 字符串中第一个字符的索引为 0,最后一个字符的索引为
str.length - 1
。
我们传递给 slice 方法的唯一参数是起始索引——要包含在新字符串中的第一个字符的索引。
传递负索引 -2 意味着给我字符串的最后 2 个字符。
这与传递 string.length - 2
作为起始索引相同。
const str = 'Hello World';
const last2 = str.slice(-2);
console.log(last2); // 👉️ ld
const last2Again = str.slice(str.length - 2);
console.log(last2Again); // 👉️ ld
slice()
方法返回一个字符串,所以最后一步是将字符串转换回数字以获得数字的最后 2 位。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。