Javascript学习笔记

前端开发中 js 常用操作

语法


变量类型 var/let/const

Link: W3C let & W3C const

letconst 是ES2015引入的两个重要的关键字,用const定义的变量和let很相似,除了const变量不能重新赋值。

1
2
3
4
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

const 和 let 有着相似的块作用域

1
2
3
4
5
6
7
8
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10

const变量必须在声明的时候赋值,

1
2
3
4
5
const PI;
PI = 3.14159265359; // Error

const PI = 3.14159265359; // Correct

const很容易令人误解,const定义的不是常量,而是对一个值的常量引用,因此,不能改变const定义的常量原始的值,却可以改变常量对象的属性,但是仍然不能给const声明的引用重新赋对象

1
2
3
4
5
6
7
8
9
10
11
12
13
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";

const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR

函数


类型判断

Object instanceof Type

1
2
3
4
5
6
7
8
9
var arr = ['A', 'B', 'C']
arr instanceof Array
| arr.constructor === Array
| (arr.prop && arr.prop.constructor === Array)

var auto = new Car('Honda', 'Accord', 1998)
auto instanceof Car
auto instanceof Object

typeof Object

1
2
3
4
5
6
7
8
9
10
11
12
console.log(typeof 42);
// expected output: "number"

console.log(typeof 'blubber');
// expected output: "string"

console.log(typeof true);
// expected output: "boolean"

console.log(typeof declaredButUndefinedVariable);
// expected output: "undefined";

格式化

1
2
3
4
5
6
7
8
// 排序 arr => ['A', 'B', 'C']
var arr = ['B', 'C', 'A']
arr.sort()


// array转string arr => 'A,B,C'
arr.join()

合并Object

合并两个对象的属性

1
2
3
// merge b with a
a = Object.assign({}, a, b)

array

1
2
3
4
5
6
7
8
9
10
11
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

var filtered = array.filter(function(value, index, arr){

return value > 5;

});

//filtered => [6, 7, 8, 9]
//array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

数组拼接

1
2
3
4
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);