我想限制两个值之间的数字,我知道在 PHP 中你可以这样做:
I want to limit a number between two values, I know that in PHP you can do this:
$number = min(max(intval($number), 1), 20);
// this will make $number 1 if it's lower than 1, and 20 if it's higher than 20
我怎样才能在 javascript 中做到这一点,而不必编写多个 if 语句和类似的东西?谢谢.
How can I do this in javascript, without having to write multiple if statements and stuff like that? Thanks.
这样的
var number = Math.min(Math.max(parseInt(number), 1), 20);
function limitNumberWithinRange(num, min, max){
const MIN = min || 1;
const MAX = max || 20;
const parsed = parseInt(num)
return Math.min(Math.max(parsed, MIN), MAX)
}
alert(
limitNumberWithinRange( prompt("enter a number") )
)
这篇关于如何使用 JavaScript 限制最小值/最大值之间的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)