JavaScript对象
对象是JavaScript的特性之一,是一种非常重要的数据类型,是自我包含的数据集合。
常用内置对象
Date
创建data对象
new Date() |
new Date(month dd, yyyy hh:mm:ss); |
new Date(yyyy, mth, dd, hh, mm, ss); |
new Date(yyyy,mth,dd) |
new Date(ms); |
Date对象获取时间细节方法:
getDate() | 从Date对象返回一个月中的某一天(1~31) |
getDay() | 从Date对象返回一周中的某一天(0~6) |
getMonth() | 从Date对象返回月份(0~11) |
getFullYear() | 从Date对象以四位数字返回年份 |
getHours() | 返回Date对象的小时(0~23) |
getMinutes() | 返回Date对象的分钟(0~59) |
getSeconds() | 返回Date对象的秒数(0~59) |
getTime() | 返回1970年1月1日至今的秒数 |
Date对象设置时间方法:
setDate() | 设置Date对象中月的某一天(1~31) |
setMonth() | 设置Date对象中月份(0~11) |
setFullYear() | 设置Date对象中的年份(四位数字) |
setHours() | 设置Date对象中的小时(0~23) |
setMinutes() | 设置Date对象中的分钟(0~59) |
setSeconds() | 设置Date对象中的秒钟(0~59) |
setMilliseconds() | 设置Date对象中的毫秒(0~999) |
Math对象的常用方法
abs(x) | 返回数的绝对值 |
ceil(x) | 对数进行上舍入 |
floor(x) | 对数进行下舍入 |
max(x,y) | 返回x和y中的最大值 |
min(x,y) | 返回x和y中的最小值 |
pow(x,y) | 返回x的y次幂 |
random() | 返回0~1之间的随机数 |
round(x) | 把数四舍五入为最近的整数 |
sqrt(x) | 返回数的平方根 |
示例:
<!--JavaScript常用内置对象的使用-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>常用内置对象使用</title>
<script type="text/javascript">
//date对象
var date = new Date();
//显示本地对象
document.write(date.toLocaleString() + "<br/>");
//Math
document.write(Math.floor(3.5));
</script>
</head>
<body>
</body>
</html>
对象的创建
JavaScript中创建对象主要有3种方式
- 使用new关键字调用构造器创建对象(通过构造函数)
function Student(name,age){ this.name=name; this.age=age; } var s1 = new Student();//没有传入参数 var s2 = new Student("Jane", 30); document.write(s1.name + "--" + s1.age + "<br/>"); document.write(s2.name + "--" + s2.age);
- 使用Object直接创建对象
var myObj = new Object(); myObj.name = "Jane"; myObj.age = 34; myObj.info = function () { document.write("My name is: " + this.name + "<br/>"); }
- 使用JSON语法创建对象
- JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写。
- JSON格式(由大括号括起来,内含多个名值对,名值对用逗号隔开,名对对应的值可以时各种数据类型,也可以是JSON对象,JSON数组用"[]"括起来)
{"name" : "Brett", "age" : "40, "email": "brett@newInstance.com"}
- 实验JSON创建对象的语法
object = {属性名1:属性值1,属性名2:属性值2,...}
- 示例
var p = { name:"zhang", gender:"male", info:function(){ document.write("name: " + this.name + ", gender: " + this.gender); } } p.info();
示例
<!--JavaScript对象的创建-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>对象的创建</title>
<script type="text/javascript">
//对象的创建方式
//1.通过构造函数
//构造函数
function Student(name,age) {
this.name = name; //隐式的变量声明
this.age = age;
}
//创建
var stu1 = new Student();
stu1.name = "xiaoming"; //先创建在赋值
stu1.age = 15;
document.write(stu1.name + "," + stu1.age + "<br/>");
var stu2 = new Student("tom", 16);
document.write(stu2.name + "," + stu2.age + "<br/>");
//2. 通过Object创建对象
var stu3 = new Object();
stu3.name = "Mar";
stu3.age = 13;
stu3.info = function () {
return this.name +"," + this.age;
}
document.write(stu3.info() + "<br/>");
//3.通过JSON创建对象
var stu4 = {
name : "Mary",
age : 18,
info: function () {
return this.name +"," + this.age;
}
}
document.write(stu4.info()+"<br/>");
</script>
</head>
<body>
</body>
</html>