- 什么是对象
- String字符串对象
- Date 日期对象
- Array数组对象
- Math对象
什么是对象
1、JavaScript中所有的事物都是对象:字符串、数值、数组、函数。
- 每个对象都带有属性和方法
- JavaScript允许自定义对象
people = new Object();
people.name = "manman";
people.age = "30";
document.write("name:"+people.name+",age:"+people.age);
people = {name:"manman",age:"30"};
document.write("name:"+people.name+",age:"+people.age);
2、自定义对象
- 定义并创建对象实例
- 使用函数来定义对象,然后创建新的对象实例
function people(name,age) {
this.name = name;
this.age = age;
}
son = new people("manman",30)
document.write("name:"+son
.name +",age:"+son.age);
String字符串对象
String对象用于处理已有的字符串
字符串可以使用单引号与双引号
在字符串中查找字符串:indexOf():
var str = "hello world";
// document.write(str.length);
document.write(str.indexOf("world")); 打印字符串的位置,没有返回-1
- 内容匹配:match()
document.write(str.match("worl1d")); 返回为字符串或者null
- 替换字符串replace(),一个参数为被替换的字符串,一个为替换的字符串
document.write(str.replace("world","nima"));
- 字符串大小写的转换:toUppercase()/toLowerCase()
document.write(str.toUpperCase());
- 字符串转为数组 strong>split()
var str1 = "hello,jike,3d";
var s = str1.split(",");
document.write(s[1]);
Date对象:日期对象用于处理日期和时间
获得当日的日期:
var date = new Date();
document.write(date);
常用方法:
getFullYear():获取年份
getTime():获取毫秒
setFullYear():设置具体的日期
getDay():获取星期
var date = new Date();
document.write(date);
document.write(date.getFullYear());
document.write(date.getTime());
date.setFullYear(2016,5,17);
document.write(date);
- 时钟实例:
数组对象
- 数组合并
var a = ["hello","world"];
var b = ["manman","ima"];
var c = a.concat(b);
- 数组排序
var a = ["5","4","2","1","3"];
document.write(a.sort());//默认升序
document.write(a.sort(function (a,b) {
return b-a; //降序
}));
- 末尾追加
var a = ["a","b"];
a.push("c");
document.write(a);
- 反转
var a = ["a","b","c"];
document.write(a.reverse());
Math对象
四舍五入数:
document.write(Math.round(2.4));
随机数:
document.write(Math.random());
document.write(Math.random()*10);
int 值:
document.write(parseInt(Math.random() * 10));//默认从0到1
最小值:
document.write(Math.min(10,20,4,.5,100));
绝对值:
document.write(Math.abs(-10));