码迷,mamicode.com
首页 > Web开发 > 详细

JS中关于Number的用法

时间:2020-07-10 13:46:13      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:fine   引用   efi   hello   log   第一个   int   结果   val   

number数字类型

包含:常规数字,NaN

NaN

not a number:不是一个数,但是他率属于数字类型


	<script src = "test.js"></script>


	//test.js
	//console.log([val]):
	//console.log("hello word!");

	// ==:进行比较的
	console.log(‘AA‘ == NaN);//false
	console.log(10 == NaN);//false
	console.log(NaN == NaN);//false


NaN和任何值(包括自己)都不相等:NaN!=NaN,所以我们不能用相等的方式判断是否为有效数字

isNaN

检测一个值是否为非有效数字,如果不是有效数字返回ture,反之是有效数字返回false


	//isNaN([val])
	console.log(isNaN[10]);//=>false

	console.log(isNaN[‘AA‘]);//=>ture
	//Number(‘AA‘) => NaN
	//isNaN(NaN) => true

	console.log(isNaN[‘10‘]);//=>false
	//Number(‘10‘) => 10
	//isNaN(10) => false
	

如果在使用isNaN进行有效数字检测的时候,首先会验证检测的值是否为数字类型,如果不是先基于Number()这个方法,把值转换为数字类型,然后再检测

把其它类型值转换为数字类型

把字符串转换为数字,只要字符串中包含任意一个非有效数字字符(第一个点除外)结果都是NaN,空字符串会变为数字零

  • Number([val])
  • parseInt/parseFloat([val],[进制]):也是转换为数字的方法,对于字符串来说,它是从左到右依次查找有效数字字符,直到遇到非有效数字字符,停止查找(不管后面是否还是数字,都不在找了),把找到的当作数字返回

	console.log(Number(‘12.5‘));//=>12.5
	console.log(Number(‘12.5px‘));//=>NaN
	console.log(Number(1.5.5));//=>NaN
	console.log(Number(‘‘));//空=>0

	//布尔转换数字
	console.log(Number(true));//=>1
	console.log(Number(false));//=>0
	console.log(isNaN(false));//=>false

	//null->0 undefined->NaN
	console.log(Number(null));//=>0
	console.log(Number(undefined));//=>NaN

	//把引用数据类型转换为数字,是先把他基于toString方法
	console.log(Number({name:‘10‘}));//引用数据类型=>NaN
	console.log(Number({}));//=>NaN
	//{XX}.toString()=>"[object Object]"=>NaN
	cosole.log(Number([]));=>0
	//([]).toString() -> ‘‘
	console.log(Number([12]))//=>12
	//[12].toString(); -> ‘12‘
	console.log(Number([12,23]));//=>NaN
	//[12,23].toString() -> ‘12,23‘

	let str = ‘12.5px‘;
	console.log(Number(str));//=>NaN
	console.log(parseInt(str));//=>12
	console.log(pareInt(str));//=>12.5
	console.log(pareFloat(‘width:12.5px‘));//=>NaN

JS中关于Number的用法

标签:fine   引用   efi   hello   log   第一个   int   结果   val   

原文地址:https://www.cnblogs.com/lzy1/p/13278545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!