JavaScript 常用函数与方法

javascript

JavaScript 常用函数与方法

数字格式

方法 toFix()

小数四舍五入到指定位数可用方法 number.toFixed(n) 其中 n 是保留小数点后的位数

Warning

方法会返回一个字符串,以保持了数字的格式,可使用函数 Number() 将字符串转换为数字

方法 toLocaleString()

使数字表示出现逗号,如 59,124,可用方法 number.toLocaleString() 并向其传入参数 "en-US",如 salary.toLocaleString("en-US")

Math 对象

Math 是一个内置对象, 它具有多种常用的数学相关的属性和方法。

Math.floor() 方法

函数 Math.floor() 返回小于或等于一个给定数字的最大整数,即向下取整

js
Math.floor( 45.95);
// 45
Math.floor(-45.95);
// -46

Math.random() 方法

函数 Math.random() 函数返回一个浮点, 伪随机数在范围 [0,1)

可以利用该内置方法构建一个基于给定范围生成随机数的函数

js
// 返回范围 [min, max) 任意值
function random(min, max) {
  return Math.random() * (max - min) + min;
}

如果需要生成随机整数,且范围内的任何数字必须以相同的概率出现,可结合整数修约函数

js
// 返回范围 [min, max] 任意整数
function randomInteger(min, max) {
  let random = Math.random() * (max + 1 - min) + min;
  return Math.floor(random);
}

Math.round() 方法

函数 Math.round() 四舍五入返回一个整数。

交互函数

JavaScript 内置一些用户界面交互的函数,如 alert()prompt()confirm(),一般以弹出窗口的形式进行交互。

但是这些内置方法有两个限制:

  • 模态窗口的确切位置由浏览器决定,通常在页面中心。
  • 窗口的确切外观也取决于浏览器,不能修改它。

alert

函数 alert(message) 运行时会在浏览器弹出一个信息弹窗并暂停脚本,直到用户点击了「确定」。

弹出的这个带有信息的小窗口被称为 modal 模态窗,同时意味着用户不能与页面的其他部分(例如点击其他按钮等)进行交互,直到他们处理完窗口,如用户点击「确定」按钮。

js
alert("Hello")

prompt

函数 prompt(title, [default]) 会在浏览器弹出一个模态窗口,显示文本并有表单 input 框接收用户输入(第二个参数可选,作为表单的初始值),还提供「确认」按钮提交表单和「取消」按钮(或按 Esc 键)取消输入返回 null

js
let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`); // You are 100 years old!
Warning

用户通过表单提交的数据都会(隐式类型转换)转换为 string 字符串类型

confirm

函数 confirm(question) 在浏览器显示一个带问题的模态窗口,并提供「确认」按钮以返回 true 和 「取消」按钮(或按 Esc 键)以返回 false,用以接收用户对于问题的回答。

js
let isBoss = confirm("Are you the boss?");
isBoss;

Copyright © 2024 Ben

Theme BlogiNote

Icons from Icônes