js基础
1. 强制类型转换
1.1 其他数据类型转 String
- 使用 toString() 方法
var a = 123
var s = a.toString();
console.log(typeof s)
- 使用 String() 函数
var b = null
var s1 = String(b);
console.log(typeof s1)
1.2 其他数据类型转 Number
- 使用 Number() 函数
- 使用 parseInt() 函数
parseInt 可以将一个字符串中有效的整数提取出来
2. 对象
2.1 对象的分类
2.2 创建对象
2.2.1 使用 new 构造函数创建
var obj = new Object()
// 为对象添加属性
obj.name = "zhangsan"
obj.age = 13
obj.say = function () {
console.log("hello")
}
2.2.2 使用对象字面量
var obj1 = {
name: "zhangsan",
age: 18,
say: function () {
console.log("hello")
},
objj: {
height: 189,
weight: 90
}
}
obj1.say()
console.log(obj1.objj.weight);
2.2.3 使用构造函数创建对象
2.2.3.1 构造函数 1.0
构造函数习惯上首字母大写
function Person(name) {
this.name = name
this.hello = function () {
console.log(this.name)
}
}
var person = new Person("zhangsan");
console.log(person.name)
person.hello()
构造函数的执行流程:
- 立刻创建一个新的对象
- 将新建的对象设置为函数中的 this, 在构造函数中使用 this 指向当前新创建的对象
- 逐行执行构造函数中的代码
- 将新建的对象作为返回值返回
2.2.3.2 构造函数 2.0
function Person2(name) {
this.name = name;
}
Person2.prototype.hello = function () {
console.log(this.name)
}
var person2 = new Person2("lisi");
person2.hello()
类似于静态, 将对象共有的属性方法抽取出去, 放入的原型对象中.
2.3 访问对象属性
2.3.1 使用 .
2.3.2 使用 [ ]
console.log(obj["age"])
3. 函数
3.1 函数创建
- 方式 1
function fun1() {
console.log("hello function")
}
fun1()
- 方式 2
var fun2 = function () {
console.log("hello function2")
}
fun2()
3.2 立即执行函数
(function (a,b) {
console.log(a + b);
})(1,3)
4. class
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
使用 class 实现
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
class的定义包含了构造函数constructor和定义在原型对象上的函数hello()(注意没有function关键字),这样就避免了Student.prototype.hello = function () {…}这样分散的代码。
最后,创建一个Student对象代码和前面章节完全一样:
var xiaoming = new Student('小明');
xiaoming.hello();
class 继承
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 记得用super调用父类的构造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
5. 数组
5.1 创建数组
- new Array
var arr = new Array()
var arr2 = new Array(1,2,3)
var arr3 = new Array(10)
console.log(arr)
arr[0] = 'aa'
arr[1] = 21
- 字面量 [ ]
var arr2 = [1.2,3,'o']