当前位置: 首页 > news >正文

JavaScripte最经典和权威的教程(对象介绍)

摘自http://www.w3schools.com/js/js_obj_intro.asp

JavaScript Objects Introduction

JavaScript is an Object Oriented Programming (OOP) language.

An OOP language allows you to define your own objects and make your own variable types.


Object Oriented Programming

JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types.

However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript object in detail.

Note that an object is just a special kind of data. An object has properties and methods.


Properties

Properties are the values associated with an object.

In the following example we are using the length property of the String object to return the number of characters in a string:

<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)
</script>

The output of the code above will be:

12


Methods

Methods are the actions that can be performed on objects.

In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:

<script type="text/javascript">
var str="Hello world!"
document.write(str.toUpperCase())
</script>

The output of the code above will be:

HELLO WORLD!

JavaScript String Object


The String object is used to manipulate a stored piece of text.


Examples

Return the length of a string
How to use the length property to find the length of a string.

Style strings
How to style strings.

The indexOf() method
How to use the indexOf() method to return the position of the first occurrence of a specified string value in a string.

The match() method
How to use the match() method to search for a specified string value within a string and return the string value if found

Replace characters in a string - replace()
How to use the replace() method to replace some characters with some other characters in a string.


Complete String Object Reference

For a complete reference of all the properties and methods that can be used with the String object, go to our complete String object reference.

The reference contains a brief description and examples of use for each property and method!


String object

The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a string:

var txt="Hello world!"
document.write(txt.length)

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a string to uppercase letters:

var txt="Hello world!"
document.write(txt.toUpperCase())

The code above will result in the following output:

HELLO WORLD!

JavaScript Date Object

The Date object is used to work with dates and times.


Examples

Return today's date and time
How to use the Date() method to get today's date.

getTime()
Use getTime() to calculate the years since 1970.

setFullYear()
How to use setFullYear() to set a specific date.

toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.

getDay()
Use getDay() and an array to write a weekday, and not just a number.

Display a clock
How to display a clock on your web page.


Complete Date Object Reference

For a complete reference of all the properties and methods that can be used with the Date object, go to our complete Date object reference.

The reference contains a brief description and examples of use for each property and method!


Defining Dates

The Date object is used to work with dates and times.

We define a Date object with the new keyword. The following code line defines a Date object called myDate:

var myDate=new Date()

Note: The Date object will automatically hold the current date and time as its initial value!


Manipulate Dates

We can easily manipulate the date by using the methods available for the Date object.

In the example below we set a Date object to a specific date (14th January 2010):

var myDate=new Date()
myDate.setFullYear(2010,0,14)

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date()
myDate.setDate(myDate.getDate()+5)

Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!


Comparing Dates

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2010:

var myDate=new Date()
myDate.setFullYear(2010,0,14)
var today = new Date()
if (myDate>today)
alert("Today is before 14th January 2010")
else
alert("Today is after 14th January 2010")

JavaScript Array Object

The Array object is used to store a set of values in a single variable name.


Examples

Create an array
Create an array, assign values to it, and write the values to the output.

For...In Statement
How to use a for...in statement to loop through the elements of an array.

Join two arrays - concat()
How to use the concat() method to join two arrays.

Put array elements into a string - join()
How to use the join() method to put all the elements of an array into a string.

Literal array - sort()
How to use the sort() method to sort a literal array.

Numeric array - sort()
How to use the sort() method to sort a numeric array.


Complete Array Object Reference

For a complete reference of all the properties and methods that can be used with the Array object, go to our complete Array object reference.

The reference contains a brief description and examples of use for each property and method!


Defining Arrays

The Array object is used to store a set of values in a single variable name.

We define an Array object with the new keyword. The following code line defines an Array object called myArray:

var myArray=new Array()

There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).

1:

var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

You could also pass an integer argument to control the array's size:

var mycars=new Array(3)
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

2:

var mycars=new Array("Saab","Volvo","BMW")

Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.


Accessing Arrays

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The following code line:

document.write(mycars[0])

will result in the following output:

Saab


Modify Values in Existing Arrays

To modify a value in an existing array, just add a new value to the array with a specified index number:

mycars[0]="Opel"

Now, the following code line:

document.write(mycars[0])

will result in the following output:

Opel

JavaScript Boolean Object

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).


Examples

Check Boolean value
Check if a Boolean object is true or false.


Complete Boolean Object Reference

For a complete reference of all the properties and methods that can be used with the Boolean object, go to our complete Boolean object reference.

The reference contains a brief description and examples of use for each property and method!


Boolean Object

The Boolean object is an object wrapper for a Boolean value.

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

We define a Boolean object with the new keyword. The following code line defines a Boolean object called myBoolean:

var myBoolean=new Boolean()

Note: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string "false")!

All the following lines of code create Boolean objects with an initial value of false:

var myBoolean=new Boolean()
var myBoolean=new Boolean(0)
var myBoolean=new Boolean(null)
var myBoolean=new Boolean("")
var myBoolean=new Boolean(false)
var myBoolean=new Boolean(NaN)

And all the following lines of code create Boolean objects with an initial value of true:

var myBoolean=new Boolean(true)
var myBoolean=new Boolean("true")
var myBoolean=new Boolean("false")
var myBoolean=new Boolean("Richard")
 

JavaScript Math Object

The Math object allows you to perform common mathematical tasks.


Examples

round()
How to use round().

random()
How to use random() to return a random number between 0 and 1.

max()
How to use max() to return the number with the highest value of two specified numbers.

min()
How to use min() to return the number with the lowest value of two specified numbers.


Complete Math Object Reference

For a complete reference of all the properties and methods that can be used with the Math object, go to our complete Math object reference.

The reference contains a brief description and examples of use for each property and method!


Math Object

The Math object allows you to perform common mathematical tasks.

The Math object includes several mathematical values and functions. You do not need to define the Math object before using it.


Mathematical Values

JavaScript provides eight mathematical values (constants) that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.

You may reference these values from your JavaScript like this:

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E


Mathematical Methods

In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available.

Examples of functions (methods):

The following example uses the round() method of the Math object to round a number to the nearest integer:

document.write(Math.round(4.7))

The code above will result in the following output:

5

The following example uses the random() method of the Math object to return a random number between 0 and 1:

document.write(Math.random())

The code above can result in the following output:

	document.write(Math.random())
	0.5300708076970763

The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10:

document.write(Math.floor(Math.random()*11))

The code above can result in the following output:

	document.write(Math.floor(Math.random()*11))
	5

JavaScript HTML DOM Objects

In addition to the built-in JavaScript objects, you can also access and manipulate all of the HTML DOM objects with JavaScript.


More JavaScript Objects

Follow the links to learn more about the objects and their collections, properties, methods and events.

ObjectDescription
WindowThe top level object in the JavaScript hierarchy. The Window object represents a browser window. A Window object is created automatically with every instance of a <body> or <frameset> tag
NavigatorContains information about the client's browser
ScreenContains information about the client's display screen
HistoryContains the visited URLs in the browser window
LocationContains information about the current URL


The HTML DOM

The HTML DOM is a W3C standard and it is an abbreviation for the Document Object Model for HTML.

The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents.

All HTML elements, along with their containing text and attributes, can be accessed through the DOM. The contents can be modified or deleted, and new elements can be created.

The HTML DOM is platform and language independent. It can be used by any programming language like Java, JavaScript, and VBScript.

Follow the links below to learn more about how to access and manipulate each DOM object with JavaScript:

ObjectDescription
DocumentRepresents the entire HTML document and can be used to access all elements in a page
AnchorRepresents an <a> element
AreaRepresents an <area> element inside an image-map
BaseRepresents a <base> element
BodyRepresents the <body> element
ButtonRepresents a <button> element
EventRepresents the state of an event
FormRepresents a <form> element
FrameRepresents a <frame> element
FramesetRepresents a <frameset> element
IframeRepresents an <iframe> element
ImageRepresents an <img> element
Input buttonRepresents a button in an HTML form
Input checkboxRepresents a checkbox in an HTML form
Input fileRepresents a fileupload in an HTML form
Input hiddenRepresents a hidden field in an HTML form
Input passwordRepresents a password field in an HTML form
Input radioRepresents a radio button in an HTML form
Input resetRepresents a reset button in an HTML form
Input submitRepresents a submit button in an HTML form
Input textRepresents a text-input field in an HTML form
LinkRepresents a <link> element
MetaRepresents a <meta> element
OptionRepresents an <option> element
SelectRepresents a selection list in an HTML form
StyleRepresents an individual style statement
TableRepresents a <table> element
TableDataRepresents a <td> element
TableRowRepresents a <tr> element
TextareaRepresents a <textarea> element

相关文章:

  • 自定义注解的简单用法
  • FreeBSD-STABLE 居然是开发用的分支,我一直搞错了好多年...!
  • Spring Data JPA 在 SpringBoot 应用中的简单实践
  • 心与心的交流
  • SimpleDateFormat 线程不安全案例
  • BPEL和JAVA(一篇不错的BPEL入门)
  • 关于 BlockingQueue 的一些认识及资料汇总
  • 欣闻我班上的学生林健在Image Cup比赛中取得好成绩
  • C#.NET常用函数大全
  • Java基本类型简介
  • 动态调用 WebService
  • 关于 ThreadPoolExecutor 的一些资料汇总及个人认识
  • ADO.NET数据操作摘录
  • 线程池ThreadPoolExecutor的拒绝策略
  • 关于 ScheduledThreadPoolExecutor 的一些资料汇总及个人理解
  • canvas绘制圆角头像
  • ERLANG 网工修炼笔记 ---- UDP
  • github从入门到放弃(1)
  • JavaScript对象详解
  • RxJS 实现摩斯密码(Morse) 【内附脑图】
  • Tornado学习笔记(1)
  • uni-app项目数字滚动
  • Vue 2.3、2.4 知识点小结
  • vue从创建到完整的饿了么(18)购物车详细信息的展示与删除
  • WebSocket使用
  • Yeoman_Bower_Grunt
  • 翻译:Hystrix - How To Use
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 设计模式(12)迭代器模式(讲解+应用)
  • 双管齐下,VMware的容器新战略
  • 小程序 setData 学问多
  • 云栖大讲堂Java基础入门(三)- 阿里巴巴Java开发手册介绍
  • ​ubuntu下安装kvm虚拟机
  • #图像处理
  • (1/2)敏捷实践指南 Agile Practice Guide ([美] Project Management institute 著)
  • (12)Hive调优——count distinct去重优化
  • (delphi11最新学习资料) Object Pascal 学习笔记---第7章第3节(封装和窗体)
  • (转)3D模板阴影原理
  • (转)Scala的“=”符号简介
  • .bat批处理(八):各种形式的变量%0、%i、%%i、var、%var%、!var!的含义和区别
  • .NET 2.0中新增的一些TryGet,TryParse等方法
  • .NET 5.0正式发布,有什么功能特性(翻译)
  • .NET 反射的使用
  • .NET 实现 NTFS 文件系统的硬链接 mklink /J(Junction)
  • .NET:自动将请求参数绑定到ASPX、ASHX和MVC(菜鸟必看)
  • .NET企业级应用架构设计系列之开场白
  • .Net中ListT 泛型转成DataTable、DataSet
  • @Repository 注解
  • [2016.7 day.5] T2
  • [20171106]配置客户端连接注意.txt
  • [Android]Tool-Systrace
  • [AutoSar]BSW_Memory_Stack_003 NVM与APP的显式和隐式同步
  • [BZOJ 4129]Haruna’s Breakfast(树上带修改莫队)
  • [BZOJ4016][FJOI2014]最短路径树问题
  • [C/C++]数据结构 深入挖掘环形链表问题