search
HomeWeb Front-endJS TutorialJavaScript web programming------some commonly used objects

Note: The println() method used below is written in the separately imported out.js method

out.js:

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

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

In the with statement block, you can Omit the reference to the object name

var dd2 = new Date(); 

with(dd2){//在with语句块中,可以省去对象名“dd2”的引用 

var year = getFullYear(); //dd2.getFullYear() 

var month= getMonth(); //从0开始的月份数 

var day = getDate();//返回月份中的第几天 

println(year+"年"+month+"月"+day+"日 "); 

}

1. Object object

<html>
<head>
<title>Object对象的用法演示</title>
</head>
<body>
<script type="text/javascript">
	/*toString()将对象转换成字符串*/
	function show(){
		alert("show......");
	}
	//alert(show);//默认调用toString()
	//alert(show.toLocaleString());
	//alert(show.toString());
	
	var arr=[1,2,3,8];
	//alert(arr.toString());
	//alert(arr);//默认调的toString()
	
	/*valueOf(): 返回指定对象的原始值  */
	//alert(arr.valueOf());//结果和toString()一样
	//alert(show.valueOf());//结果和toString()一样
</script>
</body>
</html>

2. String object

1. Two ways to create a String object

1)var str = new String("abc123");

2)var str2 = "abcd1234";

2. Attributes in the String object

str.length: String length

3. Methods in the String object

bold(): Add Thick

fontcolor("red"): Set the color

link("http://www.hncu.net"): Set it as a hyperlink

substring(1 , 5): Take the substring [1,5), the same as Java, the left contains, the right does not contain

substr(1,5): Take the substring: starting from position 1, take 5 characters

3. Date object

1. Construction of Date object

var date = new Date(); 

println(date); //GMT格式输出 

println(date.toLocaleString());//转成本地系统的日期时间格式输出。 

println(date.toLocaleDateString()); //只有日期,没有时间

2. Parse the corresponding date element from the object

//var year = date.getYear();//过时了,尽量不用 。它是返回从1900到当前日期所经过的年份 

var year = date.getFullYear(); 

println(year); 

var month= date.getMonth(); //从0开始的月份数 

println(month); 

var day1 = date.getDay(); //返回星期中的第几天,0为星期天 

println(day1); 

var day2 = date.getDate();//返回月份中的第几天 

println(day2);

3. Request to display The "day of the week" of a certain date

function getWeekDay( num ){ 
var weeks = [&#39;星期日&#39;,&#39;星期一&#39;,&#39;星期二&#39;,&#39;星期三&#39;,&#39;星期四&#39;,&#39;星期五&#39;,&#39;星期六&#39;]; 
return weeks[num]; 
} 
var weekDay = getWeekDay( date.getDay() ); 
println(weekDay);

4. Conversion between date objects and millisecond values

var date2 = new Date(); 

var time = date2.getTime();//日期对象-->毫秒值 

println("time:"+time); 

var date3 = new Date(time); 

println(date3.toLocaleDateString());

5. Conversion between date objects and strings

//日期对象-->字符串:toLocaleString() 和 toLocaleDateString() 

//字符串-->日期 

//var strDate="9/27/15";//细节:如果年份只给两位有效数字,那是代表19**年。如果是2000年以后的年份,要给4位 

var strDate="9/27/2015 ";//细节:如果年份只给两位有效数字,那是代表19**年。如果是2000年以后的年份,要给4位 

var time = Date.parse(strDate);//返回的是毫秒数 

var d = new Date(time); 
println(d.toLocaleString());

6、日期解析错误时,抛异常

<script type="text/javascript"> 

Date.prototype.parse2 =function(str){ 

throw new Exception(); 

}; 



try{ 

var strDate2="9/27/2ewewwe15 ";//细节:如果年份只给两位有效数字,那是代表19**年。如果是2000年以后的年份,要给4位 

var time2 = Date.parse2(strDate2);//返回的是毫秒数 



}catch(e){ 

alert("日期解析错误....我给的提示...."); 

} 

</script>

四、Math 对象

Math.ceil(12.34);//向上进位

Math.floor(12.34);//向下进位

Math.round(12.54);//四舍五入

Math.pow(5,6);//5的6次方

//生成10个[0,10]范围内的随机整数
	for (var x=0;x<10;x++){
		//var n=Math.floor(Math.random()*11);//法1
		//var n=Math.round(Math.random()*10);//法2
		var n=parseInt(Math.random()*11);//法3
		println(x+": "+n);
	}

五、Global对象

Global对象中的方法是全局方法,调用时可以省略Global,直接写方法名

1、parseInt()中的基数用法----进制转换

1)将指定进制格式的字符串转换成-->10进制数

//var num = parseInt("110",10); //110 

//var num = parseInt("110",2); //6 

var num = parseInt("0x3c",16); //60

2)10进制转换成--->非10进制

var num2 = new Number(6); 

println( "num2="+ num2.toString(2) ); 

var num3 = 60; 

println( "num3="+ num3.toString(16) );

2、for(in)语句的用法

1)格式: 

for(变量 in 对象){

...//对对象中的元素进行遍历操作

}

<script type="text/javascript">
	/*
     <span style="white-space:pre">	</span>for( 变量名  in 对象 ){
    	 ...//分别对对象中的元素(属性)进行遍历操作
   <span style="white-space:pre">	</span>}
    <span style="white-space:pre">	</span>*/
    <span style="white-space:pre">	</span>//数组对象
    <span style="white-space:pre">	</span>var arr=[12,13,22,-1,56,0,9];
    <span style="white-space:pre">	</span>for (x in arr){//注意,对于数组,这里的x是下标即是0,1,2,3,...
    	<span style="white-space:pre">	</span>println(x+": "+arr[x]);
<span style="white-space:pre">	</span>}
    
<span style="white-space:pre">	</span>print("<hr/>");
	//用for...in语句操作自定义对象
	for (x in p2){//x是函数中的成员变量与成员方法的名称
		println(x+"------"+p2[x]);// p2[x]就是valeOf(x)
	}
</script>

六、自定义对象

对js来描述对象--Person

1、方法1:本质上,有点类似于Java当中的直接new一个空参对象,然后往里面直接添加变量

<script type="text/javascript"> 

function Person(){ 

//alert("Person..."); 

println("Person..."); 

} 

var p = new Person(); 

//要为Person对象p添加变量,直接使用:p.对象名=... 

p.name = "Jack"; 

p.age = 24; 

//alert(p.name+"---"+p.age); 

//要为Person对象p添加方法,直接使用:p.方法名=... 

p.show = function(){ 

println(p.name+"---"+p.age); 

}; 

p.show();//调方法 



var obj = new Object(); 

obj.name = "God"; 

obj.age =10000; 

obj.show = function(){ 

println(obj.name+"::::"+obj.age); 

}; 

obj.show(); 



</script>

2、方法2:更接近于Java当中的面向对象的方式----类的封装

<script type="text/javascript"> 

//方式2:更接近于Java当中的面向对象的方式----类的封装 

function Person(name,age){ 

this.name = name; //这里的this.表示给当前对象添加一个变量 

this.age = age; 

this.setName= function(name){ 

this.name = name; 

}; 

this.getName= function(){ 

return this.name; 

}; 

this.show= function(){ 

return "name:"+this.name+",age:"+this.age; 

}; 

} 

var p = new Person("Tom",22); 

println(p.name+"==="+p.age); 

p.setName("Rose"); 

println(p.show()); 



for(x in p){ //x为自定义对象当中的变量名 

println(x+":"+p[x]); //p[x]为自定义对象当中的变量值(如果是函数,为它的字节码) 

} 



</script>

3、方式3: map方式, key:value ----类似于java当中的数据封装,把数据封装到Map集合当中

<span style="font-weight: normal;"><script type="text/javascript">  
       //对象调用成员有两种方式:对象.属性名  和  对象["属性名"]  
       //1) 对象.属性名的方式应该注意: 如果属性名不符合标识符的命名规则,那么不能采用这种方式调用,如下面例子当中的不能采用map[8]的方式  
       //2)  对象["属性名"]的方式应该注意:如果属性名符合标识符的命名规则,那么访问时属性名应该要加引号,如下面例子当中的map[name]要写成pp["name"]的形式才行  
       var pp = {  
           //"name":"张三","age":"23", //key:value
	   name:"张三",age:"23",  //这句和上面一句等效---key的名称可以省略引号   
           "getName": function(){  
               return this.name;  
            }  
       };  
       println(pp.name+"===" + pp.age);     
       println(pp.getName());  
       println( pp["name"] ); //用 pp[name]是不行的  
         
       //map集合的定义  
       var map={  
            8:"张三" , 3:"李四", 5:"Jack"  
       };  
       var val = map[8];//8是数字,不是变量名,因此引号省略照样能解析出来
       println("val:"+val);  
       //var val2 = map.8; //不行,因为8不是变量的形式  
       //println(val2);  
         
</script> </span>

4、map数据封装的进一步扩展

<script type="text/javascript"> 

//属性值是数组 

var myMap = { 

names:["Jack1","Jack2","Jack4"], 

ages:[25,22,18] 

}; 

//取出Jack2的姓名和年龄 

println("name:"+ myMap.names[1]); 

println("age:"+ myMap.ages[1]); 



var myMap2 = { 

names:[{name:"Jack1"},{name:"Jack2"},{name:"Jack4"}] 

}; 

//取出Jack1 

println("name:"+ myMap2.names[0].name);//或者println(
myMap2.names[0]["name"]); 

</script>

5、对象的prototype属性

要给对象添加新功能时,直接采用“对象.prototype.新内容”的形式就可以。这内容可以是变量,也可以是函数。

1)为String对象添加一个自定义函数trim:剪去字符串两端的空格

<script type="text/javascript"> 

function trim(str){ 

var start, end; 

start=0; 

end=str.length-1; 

while(start<=end && str.charAt(start)==&#39; &#39;){ 

start++; 

} 

while(start<=end && str.charAt(end)==&#39; &#39;){ 

end--; 

} 

return str.substring(start,end+1); 

} 

//测试 

var s=" dsk dsds "; 

//alert("#"+s+"#"); 

//alert("#"+ trim(s) + "#" ); 



</script>

2)添加变量

String.prototype.aa = 200; 

println("abc123".aa);

3)添加函数

String.prototype.trim = trim; 

println("<hr>"); 

println("aa3".trim(" abc123 ")); 

(这里的trim就是上面(1)里面自定义属性中的trim)

注:这里通过“aa3”.trim(" abc123 ")处理的是别的字符串并不是自己

4)通过对象直接调用的函数(注意,一定要把前一版本当中的参数str改成this)

<script type="text/javascript"> 

String.prototype.trim = function(){ 

var start, end; 

start=0; 

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); 

}; 

println(" aa3 ".trim() ); 

var str2 =" 76jh dssdds "; 

println( str2.trim() ); 



</script> 

注:这里是对自己进行处理

6、对象原型修改练习

1)给String对象添加一个toCharArray()方法

2)给String对象添加一个reverse方法:将字符串反转

3)JS当中,函数内部是可以写函数的,而Java是做不到的。但Java有内部类

<script type="text/javascript"> 

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(){ 

//JS当中,函数内部是可以写函数的,而Java是做不到的。但Java有内部类 

//辅助函数,用于交换数组中的两个元素 

function swap(arr,x,y){ 

var temp = arr[x]; 

arr[x] = arr[y]; 

arr[y] = temp; 

} 



var arr = this.toCharArray(); 

for(var x=0,y=arr.length-1; x<y; x++,y--){ 

swap(arr,x,y); 

} 

return arr.join("-"); 

}; 

/* 

//辅助函数,用于交换数组中的两个元素 

function swap(arr,x,y){ 

var temp = arr[x]; 

arr[x] = arr[y]; 

arr[y] = temp; 

} 

*/ 

//测试 

var str = "dsjk2323jkjkewio"; 

println( str.reverse() ); 



//测试:在外部能否调用函数reverse内部的swap函数 

//测试结果:不行的。其实它和局部变量是一个道理。 

//因此,以后在写某个函数内部的辅助功能函数时,最好写在内部 

/* 

var arr =[23,45,7,9]; 

swap(arr,1,2); 

println("kkk"); 

println(arr); 

*/ 

</script>

 以上就是JavaScript网页编程之------一些常用的对象的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.