迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中获取数字的最后 2 位数字

作者:迹忆客 最近更新:2022/11/22 浏览次数:

要获取数字的最后 2 位数字:

  1. 将数字转换为字符串。
  2. 对字符串调用 slice() 方法,将 -2 作为参数传递给它。
  3. slice() 方法将返回字符串中的最后 2 个字符。
  4. 将字符串转换回数字以获得最后 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

JavaScript 中获取数字的最后 2 位数字

slice() 方法返回一个字符串,所以最后一步是将字符串转换回数字以获得数字的最后 2 位。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便