• 2024-11-21
宇哥博客 前端开发 js中的parseInt()和Number()详解

js中的parseInt()和Number()详解

parseInt() 函数:
如果参数是以“0x”开头,parseInt() 会把其余部分以十六进制解析。

测试代码:

<script type="text/javascript">
	var num1 = parseInt('123');		//结果:123
	var num2 = parseInt('');		//结果:NaN
	var num3 = parseInt('123.33');	//结果:123
	var num4 = parseInt('123abb');	//结果:123
	var num5 = parseInt('123.55abb');	//结果:123
	var num6 = parseInt(null);		//结果: NaN
	var num7 = parseInt(undefined);	//结果: NaN
	var num8 = parseInt('0x14');	//十六进制转为了十进制,结果:20
	var num9 = parseInt('0x14', 16);//第2个参数表示进制,结果:20
	var num10 = parseInt('1101',2);	//结果:13
	var num11 = parseInt('asd123');	//结果: NaN
	var num12 = parseInt('asd');	//结果: NaN
	var num13 = parseInt(' 123 ');		//结果:123
	var num14 = parseInt(true);	//结果:NaN
	var num15 = parseInt(false);	//结果:NaN

	console.log('num1', num1);
	console.log('num2', num2);
	console.log('num3', num3);
	console.log('num4', num4);
	console.log('num5', num5);
	console.log('num6', num6);
	console.log('num7', num7);
	console.log('num8', num8);
	console.log('num9', num9);
	console.log('num10', num10);
	console.log('num11', num11);
	console.log('num12', num12);
	console.log('num13', num13);
	console.log('num14', num14);
	console.log('num15', num15);

	//-----------------------------------------

	var num100 = Number('123');		//结果:123
	var num101 = Number('');		//结果:0
	var num102 = Number('123.33');	//结果:123.33
	var num103 = Number('123abb');	//结果:NaN
	var num104 = Number('123.55abb');	//结果:NaN
	var num105 = Number(null);		//结果: 0
	var num106 = Number(undefined);	//结果: NaN
	var num107 = Number('0x14');	//结果:20
	var num108 = Number('asd123');	//结果: NaN
	var num109 = Number('asd');	//结果: NaN
	var num110 = Number(' 123 ');		//结果:123
	var num111 = Number(true);	//结果:1
	var num112 = Number(false);	//结果:0

	console.log('num100', num100);
	console.log('num101', num101);
	console.log('num102', num102);
	console.log('num103', num103);
	console.log('num104', num104);
	console.log('num105', num105);
	console.log('num106', num106);
	console.log('num107', num107);
	console.log('num108', num108);
	console.log('num109', num109);
	console.log('num110', num110);
	console.log('num111', num111);
	console.log('num112', num112);
</script>

运行截图:

本文来自网络,不代表本站立场,转载请注明出处。https://www.ygbks.com/2539.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

返回顶部