廖雪峰JavaScript练习题

练习:不要使用JavaScript内置的parseInt()函 数,利用map和reduce操作实现一个string2int()函数:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<style type="text/css"></style>
</head>
<body>

		<script type="text/javascript">
			function string2int(s) {
				var l = [];
				for (var i = 0; i < s.length; i++) {

					l.push(s[i]*1)
				}
			
				return (
					l.reduce(function(x,y) {
						return x*10+y;
					})
					)
			}
			if (string2int('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) {
				if (string2int.toString().indexOf('parseInt') !== -1) {
					console.log('请勿使用parseInt()!');
				}
				else if (string2int.toString().indexOf('Number') !== -1) {
					console.log('请勿使用Number()!');
				}
				else {
					console.log('测试通过!');
				}
			}
			else {
				console.log('测试失败!');
			}
		</script>

</body>
</html>

  

猜你喜欢

转载自www.cnblogs.com/hys-blog/p/10013645.html