JavaScript:基础总结

JavaScript 数据类型

  1. JavaScript数据类型有这么几种:number、string、boolean、undefined(只有一个值undefined,在变量声明但没有初始化的时候,默认值就是undefined)、null(你可以理解为指向空对象的指针)、object。
  2. NaN 是number类型,小数点前边是0的小数0可以省略,NaN的判断请用函数isNaN(),别的都不好使。
  3. typeof 关键字可以用字符串输出变量的类型(以字符串形式)。
  4. instanceof 关键字可以判断某个实例是不是某个类。
  5. null instanceof object == false 。
  6. typeof null 的结果是“object”。
  7. 函数名也是指向函数的一个指针(类似于C++的函数指针),所以,函数名 instanceof Function == true。
  8. 所有引用类型(当然除了空指针null)都是Object的实例,所有的函数都是Function的实例。
  9. 浮点数比较大小请用差值和阈值比较,别用更别用=。
  10. ==比较的是值相不相等,===比较的是类型和值都要相等。
function printInfo(obj){
	console.log(obj + "是" + typeof obj);
}

printInfo(12);  //number
printInfo(12.2); //number
printInfo(.23); //number
printInfo(2.2e-2); //number
printInfo(NaN);  // number
printInfo(Infinity); // number

printInfo(undefined); // undefined
printInfo("123");  // string
printInfo("undefined"); //string

var arr = [1,2,3];
printInfo(arr); // object
printInfo(null); // null
printInfo(true);  // boolean
printInfo(2 > 3); // boolean
printInfo(printInfo); // function

console.log(printInfo instanceof Function); // true
console.log(printInfo instanceof Object); // true
console.log(Function  instanceof Object); // true

var a;// 声明但未初始化
console.log(a); // undefined
console.log(a === undefined); // true

console.log(1/3 == (1 - 2/3)); //  false
console.log((1/3 - (1 - 2/3)) < 0.000001);  //  true

console.log("123" == 123); // true
console.log("123" === 123); // false

万物皆对象

  1. 一切引用类型都是Object的实例,那基本类型咋办?Java咋做的,引入了包装类(比如int 和 Integer,double 和 Double),js也这么干了,number和Number, string和String,boolean和Boolean,所以在JavaScript中,万物皆对象这句话没问题。
  2. 更牛逼的是,基本类型竟然能够使用引用类型的方法!你比如在String.prototype添加方法,基本类型string的字符串也能使用(个人觉得可能是原型把基本类型自动转成引用类型了)。
String.prototype.myfunction = function(){
	console.log("我是新添加的方法");
}

var str1 = "abc";
var str2 = new String("abc");
var str3 = String("abc");

console.log(typeof str1); // string
console.log(typeof str2); // object 引用类型
console.log(typeof str3); // string
// 以下三句话都没报错
str1.myfunction(); 
str2.myfunction();
str3.myfunction();


Number.prototype.newfunction = function(){
	console.log("我也是新添加的方法");
}
var number1 = 1;
var number2 = new Number(1);
var number3 = Number(1);

console.log(typeof number1); // number
console.log(typeof number2); // object 引用类型
console.log(typeof number3); // number

number1.newfunction();
number2.newfunction();
number3.newfunction();

JS常用的类(以后细说)

  1. Array(我个人管它叫列表,受Java影响,数组都是不可变长度)
  2. Date(日期类)
  3. String(字符串)
  4. Math(数学操作)

Array

var list = []; 
// 增  push(从最后增)
list.push(1);
list.push("123");
console.log(list); // [1,123]

// 删  pop(从最后删)
list.pop();
console.log(list); // [1]

// 改 必须知道下标
list.push(new Date());
list.push("string");
list.push({});
console.log(list); // [1,Mon Jul 30 2018 22:15:53 GMT+0800 ,"string",{}]
list[1] = "123";
console.log(list); // [1,123,"string",{}]

// 查 indexOf(str, index)
var arr = ['aa','cc','bb','cc','dd'];
var re = arr.indexOf('cc'); //1
var re2 = arr.indexOf('cc',2); //3

// 合并 不会改变数组本身
var arr1 = [1,2,3];
var arr2 = [4,5,6];
console.log(arr1.concat(arr2));  // [1,2,3,4,5,6]
console.log(arr1); //[1,2,3]

// 删除和替换 会改变数组本身
var arr1 = [0,1,2,3,4,5,6,7];
arr1.splice(0,2,"a","b");// 从index=0开始 删除2个,并用"a","b"替换
console.log(arr1.toString()); //a,b,2,3,4,5,6,7
arr1.splice(0,0,"c"); // 从index=0开始 删除0个 添加"c"
console.log(arr1.toString()); //c,a,b,2,3,4,5,6,7

// 翻转 会改变数组本身
console.log(arr1);  // ["c", "a", "b", 2, 3, 4, 5, 6, 7]
console.log(arr1.reverse()); // [7, 6, 5, 4, 3, 2, "b", "a", "c"]
console.log(arr1);  // [7, 6, 5, 4, 3, 2, "b", "a", "c"]

// 截取 不会改变数组本身
console.log(arr1);  // [7, 6, 5, 4, 3, 2, "b", "a", "c"]
console.log(arr1.slice(1,5)); // [6, 5, 4, 3]
console.log(arr1);  // [7, 6, 5, 4, 3, 2, "b", "a", "c"]

// 连接数组元素 不会改变数组本身 如果参数省略则用逗号分隔
console.log(arr1);  // [7, 6, 5, 4, 3, 2, "b", "a", "c"]
console.log(arr1.join("-")); // 7-6-5-4-3-2-b-a-c 
console.log(arr1);  // [7, 6, 5, 4, 3, 2, "b", "a", "c"]

Date



// getFullYear() :返回Date对象的年份值;4位年份。
// getMonth() :返回Date对象的月份值。从0开始,所以真实月份=返回值+1 。
// getDate() :返回Date对象的月份中的日期值;值的范围1~31 。
// getHours() :返回Date对象的小时值。
// getMinutes() :返回Date对象的分钟值。
// getSeconds() :返回Date对象的秒数值。
// getMilliseconds() :返回Date对象的毫秒值。
// getDay() :返回Date对象的一周中的星期值;0为星期天,1为星期一、2为星期二,依此类推
var date = new Date();
var a = date.getDate();
console.log("===getDate===:"+a); //30
var b = date.getDay();
console.log("===getDay===:"+b); // 1
var c = date.getFullYear();
console.log("===getFullYear===:"+c); // 2018
var d = date.getHours();
console.log("===getHours===:"+d); // 22
var e = date.getMilliseconds(); 
console.log("===getMilliseconds===:"+e);  //213
var f = date.getMinutes();
console.log("===getMinutes===:"+f); //57
var g = date.getMonth();
console.log("===getMonth===:"+g); // 6
var h = date.getSeconds();
console.log("===getSeconds===:"+h); //37
var k = date.getUTCDate();
console.log("===getUTCDate===:"+k); // 30
var l = date.getUTCDay();
console.log("===getUTCDay===:"+l); //1
var m = date.getUTCFullYear();
console.log("===getUTCFullYear===:"+m); //2018

var o = date.toDateString();
console.log("===toDateString===:"+o); // Mon Jul 30 2018
var p = date.toISOString();
console.log("===toISOString===:"+p);// 2018-07-30T14:59:46.228Z
var q = date.toJSON();
console.log("===toJSON===:"+q); // 2018-07-30T14:59:46.228Z 
var r = date.toLocaleDateString();
console.log("===toLocaleDateString===:"+r); // 2018/7/30
var s = date.toLocaleString();
console.log("===toLocaleString===:"+s); //2018/7/30 下午10:59:10
var t = date.toLocaleTimeString();
console.log("===toLocaleTimeString===:"+t); //下午10:59:10
var u = date.toTimeString();
console.log("===toTimeString===:"+u); // 22:59:10 GMT+0800 (中国标准时间)


var dt = new Date();
console.log(dt.toString()); // => Tue Dec 23 2014 22:56:11 GMT+0800 (中国标准时间) :将Date转换为一个'年月日 时分秒'字符串
console.log(dt.toLocaleString()); // => 2014年12月23日 下午10:56:11  :将Date转换为一个'年月日 时分秒'的本地格式字符串
 
console.log(dt.toDateString()); // => Tue Dec 23 2014 :将Date转换为一个'年月日'字符串
console.log(dt.toLocaleDateString()); // => 2014年12月23日 :将Date转换为一个'年月日'的本地格式字符串
 
console.log(dt.toTimeString()); // => 22:56:11 GMT+0800 (中国标准时间) :将Date转换为一个'时分秒'字符串
console.log(dt.toLocaleTimeString()); // => 下午10:56:11 :将Date转换为一个'时分秒'的本地格式字符串
 
console.log(dt.valueOf()); // => 返回Date对象与'1970/01/01 00:00:00'之间的毫秒值(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')

String

var str = "1234string23e240";

console.log(str.charAt(1));  // 返回index = 2的字符
console.log(str[1]);  // 跟上边一样

console.log(str.indexOf("23")); // 1
console.log(str.lastIndexOf("23")); // 10 

console.log(str.replace("12","--"));  //--34string23e240 不会改变str原有的值
console.log(str); //1234string23e240

console.log(str.slice(0,5)); //1234s 字符串切片
console.log(str.split("string")); //["1234", "23e240"] 分割成string数组

console.log(str.toUpperCase()); // 1234STRING23E240 不改变原值
console.log(str); // 1234string23e240
console.log(str.toLowerCase()); //1234string23e240 不改变原值
console.log(str); //1234string23e240

str = "   sdfasfdf  fdssfsd  ";
console.log(str.trim());  // sdfasfdf  fdssfsd  去掉空格 不改变原值
console.log(str); //

Math

var rand = Math.random(); //  返回0-1随机数
console.log(Math.floor(2.15)); // 2 舍
console.log(Math.ceil(2.15)); // 3 进一
console.log(Math.round(3.14)); // 3 四舍五入

JSON

var jsonStr = '{ "name": "haorooms", "sex": "man" }';
var jsonObj = { "name": "haorooms", "sex": "man" };
console.log(typeof jsonStr);  // string
console.log(typeof jsonObj);  // object


// json字符串转json对象
var obj1 = JSON.parse(jsonStr);
console.log(obj1);
console.log(typeof obj1); // object

// json对象转json字符串
var str1 = JSON.stringify(jsonObj);
console.log(str1);
console.log(typeof str1); // string 
/*新版本的 JSON 修改了 API,
将 JSON.stringify() 和 JSON.parse() 都注入到了 Javascript 的内建对象里面,
前者变成了 Object.toJSONString(),而后者变成了 String.parseJSON()。
如果提示找不到toJSONString()和parseJSON()要领,则说明您的json包版本太低。*/

JS面向对象

  1. js是动态语言,可以动态添加属性和方法!!!
  2. js本身没有class的概念,但是可以通过原型等方法实现面向对象(封装、继承、多态)。
  3. 通过类名,new出一个对象的过程,叫做"类的实例化"。
  4. this关键字是指向自己的一个指针,在类中,必须使用this.属性或者方法名访问。谁调用了函数,this就指向谁。
  5. constructor返回对象的构造函数,instanceof 用来判断该对象是否是这个类的实例。
  6. this的指向问题:
    ①通过函数名()调用的,this永远指向window
    ②通过对象.方法调用的,this指向这个对象。
    ③函数作为数组中的一个元素,用数组下标调用的,this指向这个数组
    ④函数作为window内置函数的回调函数使用,this指向window。
    setInterval setTimeout 等。
    ⑤函数作为构造函数,使用new关键字调用,this指向新new出的对象。
/*javascrpit 面向对象*/


// 直接用new Object创建对象 动态添加属性
var person = new Object();  // 或者var persnn = {};
person.name = "张三";
person.age = 20;
person.job = "程序员";
person.sayName = function(){
	console.log(this.name);  //必须加this
}

person.sayName(); //张三

// 和下面的写法是一模一样的
person = {
	name : '张三',
	age : 20,
	job : '程序员',
	sayName : function(){
		console.log(this.name);  //必须加this
	}
};
person.sayName(); // 张三

person.name = "123";
person.sayName();  // 123
console.log(person.constructor); // Object()


// 用工厂创建对象
function createPerson(name,age,job){
	var p = {};
	p.name = name;
	p.age = age;
	p.job = job;
	p.sayName = function(){
		console.log(this.name);
	}
	return p;
}

var p = createPerson('李四',21,'java程序员');
p.sayName();
console.log(p.constructor);  //Object()

// 通过构造函数创建对象
function Person(name,age,job){
	this.name = name;
	this.age = age;
	this.job = job;
}
// 这样写的好处是 每一个Person实例公用这一段代码 
Person.prototype.sayName = function(){
	console.log(this.name);
}
var person1 = new Person('王五',22,'php程序员');
var person2 = new Person('赵六',30,'技术经理');
person1.sayName();
console.log(person1.constructor);  // function Person(name,age,job)...
console.log(person1 instanceof Person);  // true
console.log(person1 instanceof Object);  // true
console.log(person1.sayName === person2.sayName);  // true

// person1 和 person2 有一个隐含的属性 是一个指针 指向Person.prototype
console.log(person1.prototype);  // undefined
console.log(Person.prototype.isPrototypeOf(person1));  // true
console.log(Person.prototype.isPrototypeOf(person2));  // true

// 其实person1 和 它的构造函数没有什么关系 和原型有关
// 原型最初只包含constructor属性 其他的属性都是继承Object得到的,并且constructor属性是共享的 所以实例也能访问constructor属性
console.log(Object.getPrototypeOf(person1)  === Person.prototype);  // true
console.log(Object.getPrototypeOf(person1)  == Person); // false


// 在另一个对象的作用域中调用 
var o = new Object();
Person.call(o, "Kristen", 25, "Nurse");
// o.sayName(); // 会报错 因为o是Object 而不是Person
console.log(o.constructor);  // Object()
console.log(o.name);
console.log(o.age);
console.log(o.job);

// JavaScript 继承
function Animal (name,sex) {
  this.name = name || 'Animal';
  this.sex = sex ;
  this.sleep = function(){
    console.log(this.name + '正在睡觉!');
  }
}
Animal.prototype.eat = function(food) {
  console.log(this.name + '正在吃:' + food);
};

function Cat(name,sex,age){
  Animal.call(this,name,sex); //通过call函数改变this的指向
  this.age = age || '20';
  this.name = name || 'Tom';
}

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

// Test Code
var cat = new Cat("小猫","female","25");
console.log(cat.name); // tom
cat.sleep(); // 小猫正在睡觉
cat.eat("fish"); // 小猫正在吃fish
console.log(cat.sex); //female
console.log(cat.age); //25
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
console.log(cat); 



// JavaScript多态
function People(name){
	this.name = name;
}
People.prototype.learning = function(){
	console.log("I am a people, I am learning");
}

function Student(name,studentId){
	People.call(this,name)
	this.studentId = studentId;
	Student.prototype = new People();
	Student.prototype.constructor =  Student;
}
Student.prototype.learning = function(){
	console.log("I am a student, I am learning");
}
function Worker(name,workerId){
	People.call(this,name);
	this.workerId = workerId;
	Worker.prototype = new People();
	Worker.prototype.constructor = Worker;
}
Worker.prototype.learning = function(){
	console.log("I am a worker, I am learning");
}

function peopleFactory(type){
	switch (type){
		case "student":
			return new Student();
			break;
		case "worker":
			return new Worker();
			break;
		default:
			return new People();
			break;
	}
}

var person = peopleFactory("student");
person.learning(); //I am a student, I am learning
person = peopleFactory("worker");
person.learning(); //I am a worker, I am learning


猜你喜欢

转载自blog.csdn.net/tsfx051435adsl/article/details/81271566
今日推荐