Home Web Front-end JS Tutorial Part 1 Quick Start—Date, Math, and Global objects in js basic practice

Part 1 Quick Start—Date, Math, and Global objects in js basic practice

Jul 28, 2018 am 10:41 AM

tool.js

function print(str){
	document.write(str);
}

function println(str){
	document.write(str+"<br/>");
}

///////通过prototype属性扩展js API的对象的功能/////////

//※把trim方法融入到String对象中: str.trim()
String.prototype.trim = function(){
	 var start=0;//第一个非空格字符的位置
	 var end=this.length-1;//最后一个非空格字符的位置
	 while(start<=end && this.charAt(start)==&#39; &#39;){
		 start++;
	 }
	 while(start<=end && this.charAt(end)==&#39; &#39;){
		 end--;
	 }
	 return this.substring(start,end+1);
};

//给String对象添加一个toCharArray()方法
String.prototype.toCharArray = function(){
	var chs=[];
	for(var x=0;x<this.length;x++){
		chs[x]=this.charAt(x);
	}
	return chs;
};

//给String对象添加一个reverse()方法
String.prototype.reverse = function(){
	//函数内部可以再定义函数----Java做不到
	function swap(arr,start,end){
		var temp=arr[start];
		arr[start]= arr[end];
		arr[end] = temp;
	}
	
	var arr = this.toCharArray();
	for(var start=0,end=arr.length-1; start<end; start++,end--){
		swap(arr,start,end);
	}
	return arr.join("");
};
String.prototype.compareTo=function(str){
	if(typeof(str)!="string"){
		return 1;
	}
	
	var len1=this.length;
	var len2=str.length;
	var shortLen=len1>len2?len2:len1;
	var longLen=len1>len2?len1:len2;
	for(var i=0; i<shortLen; i++){
		if(this.charAt(i)!=str.charAt(i)){
			return this.charAt(i)-str.charAt(i);
		}
	}
	if(len1>len2){
		return 1;
	}else if(len1<len2){
		return -1;
	}else{
		return 0;
	}
	
};


//为数组对象的shift()和unshift()函数取两个我们习惯的别名
Array.prototype.removeFirst=function(){
	return this.shift();
};

Array.prototype.addFirst=function(e){
	return this.unshift(e);
};

Array.prototype.addLast=function(e){
	return this.push(e);
};
Copy after login

Objects in JS language--Date object

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS语言中的对象--Date对象</title>
<script type="text/javascript" src="tools.js"></script>
</head>
<body>
	<script type="text/javascript">
		var date = new Date();
		println(date);//date.toString()
		println(date.toDateString());//只显示日期
		println(date.toLocaleString());//本地格式
		println(date.toLocaleDateString());//本地格式:只显示日期

		var year = date.getYear(); //建议使用getFullYear()代替
		println(year); //118 = 2018-1900
		year = date.getFullYear();//※
		println(year);

		var month = date.getMonth();//※ 0~11  我们用时要 +1
		println(month);

		var day1 = date.getDay(); //※星期几, 其中星期日是0
		var day2 = date.getDate(); //※月份中的第几天,就是我们平时用的“日期”

		println(year + "." + (month + 1) + "." + day2);
	</script>

	<hr/>

	<script type="text/javascript">
		//格式转换

		//日期对象 和 毫秒值之间的转换
		var date2 = new Date();
		var time = date2.getTime(); //日期对象     毫秒值
		println("毫秒值:" + time);

		time = time + 2 * 24 * 60 * 60 * 1000;//2天后
		var date3 = new Date(time); //也可以用setTime() // 毫秒值     日期对象
		println("后天:" + date3.toLocaleString());

		//日期对象 和  字符串之间的转换
		var str = date3.toLocaleString();//日期对象      字符串

		//字符串     日期对象
		//var str = "6/27/2018"; //格式 OK
		//var str = "July 23, 2018"; //格式 OK
		//var str = "2010/08/08"; //格式 OK
		var str = "2010-08-08"; //格式 OK
		var time = Date.parse(str);
		var d = new Date(time);
		println(d.toLocaleString());
	</script>

    <hr/>
    
	<script type="text/javascript">
		/*一个小语法:
		   with(对象){
		 	 //在该区域内可以直接使用"对象"的内容(属性和方法),不需要“对象.”
		  }
		 	 
		 */
        var date=new Date();
		with (date) {
			var year = getFullYear();
			var month = getMonth() + 1;
			var day = getDate();
			println(">>> " + year + "年" + month + "月" + day + "日");
		}
	</script>
</body>
</html>
Copy after login

Objects in JS language- -Math object

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS语言中的对象--Math对象</title>
<script type="text/javascript" src="tools.js"></script>
</head>
<body>
	<script type="text/javascript">
		var x = -323.78;
		x = Math.abs(x);
		println("x=" + x);

		x = 7.89;
		x = Math.floor(x);
		println(x);//8
		x = Math.ceil(x);
		println(x);//7
		x = Math.exp(x);
		println(x);//e^2

		y = 5;
		println(Math.pow(x, y)); //x 的 y 次幂

		//round(x) 四舍五入
		println(Math.round(4.56));

		//random() 返回 0 ~ 1 之间的随机小数。
		//生成10个[1,10]范围内的随机整数
		for(var i=1;i<=10;i++){
		  	//int n = (int)(Math.random()*10) +1; //Java写法
		  	//var n = Math.floor( Math.random()*10 ) +1; //JS写法1---用Math.floor()实现取整
		  	var n=parseInt(Math.random()*10)+1;//JS写法2---用parseInt()实现取整
		  	print(n+" ");
		}
		 println("");
	</script>
</body>
</html>
Copy after login

Objects in JS language--Global object, top-level function (global function)

js puts some common functions It is defined in an object called Global, and "Global." cannot be written when calling.

eval(str): Treat the string as a js statement to evaluate and execute

Number(s): Convert the parameter s into "Value (value of type Number)", if the parameter is a Date, the millisecond value is returned. If the parameter cannot be converted into a value, it is returned: NaN

parseFloat(): Parse a string and Returns a floating point number.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS语言中的对象--Global对象, 顶层函数(全局函数)</title>
<script type="text/javascript" src="tools.js"></script>
</head>
<body>
	<script type="text/javascript">
		//js把一些通用的函数定义在一个叫Global的对象中,调用时不能写"Global."
		//eval(str): 把字符串当成js语句来进行评估且执行
		eval("x=10;y=20;document.write(x*y);");

		document.write("<br/>" + eval("2+2") + "<br/>");
		var x = 10;
		document.write(eval(x + 17) + "<br/>");

		//isNaN(s): 判断s是否是一个"非Number类型"的值
		var str = "123";
		println(isNaN(str)); //false ---不是"非Number类型"
		str = "abc123";
		println(isNaN(str)); //true ---是"非Number类型"
	</script>

	<hr />

	<script type="text/javascript">
		//Number(s): 把参数s转换成"数值(Number类型的值)",如果参数是Date则返回毫秒值,如果参数不能转换成数值则返回: NaN
		var test1 = new Boolean(true);
		var test2 = new Boolean(false);
		var test3 = new Date();
		var test4 = new String("999");
		var test5 = new String("999 888");

		document.write(Number(test1) + "<br />");
		document.write(Number(test2) + "<br />");
		document.write(Number(test3) + "<br />");
		document.write(Number(test4) + "<br />");
		document.write(Number(test5) + "<br />");

		document.write(Number.MAX_VALUE + "<br />");
		document.write(Number.MIN_VALUE + "<br />");
		document.write(Number.NEGATIVE_INFINITY + "<br />");
	</script>

	<hr />

	<script type="text/javascript">
		//parseFloat(): 解析一个字符串并返回一个浮点数。 
		var str = "3.14159";
		var val = parseFloat(str);
		val *= 2;
		println(val);

		//parseInt(): 解析一个字符串,并返回一个整数。
		//parseInt(str, radix) : 没有参数radix时为十进制

		//将字符串     十进制数
		var num = parseInt("110", 10); //10进制的字符串"110"     110
		println(num);//110
		var num = parseInt("110", 2); //2进制的字符串"110" --> 6
		println(num);//6
		var num = parseInt("110", 16); //16进制的字符串"110" --> 272
		println(num);//272

		//将十进制数 --> 其它进制格式的字符串
		var num = 100; //js自动会把一个数值包装成一个Number对象
		//NumberObject.toString(radix)
		println(num.toString(2)); //把num转换成2进制的字符串
		println(num.toString(16)); //把num转换成16进制的字符串
	
	</script>
</body>
</html>
Copy after login

Related articles:

Part 2 Quick Start—JS Basics Practical BOM--Browser Object Model, DOM

Part 3 Quick Start—JS Basic Practical Application Code Sharing

Related Videos:

27 Classic Practical Video Tutorials for Front-end JS Development-Free Online Video Tutorial

The above is the detailed content of Part 1 Quick Start—Date, Math, and Global objects in js basic practice. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles