1、變量申明方式
變量申明關鍵字:let和const,拋棄var
let與const都是隻在聲明所在的塊級作用域內有效。
let聲明的變量可以改變,值和類型都可以改變,沒有限制。
const聲明的變量不得改變值,這意味着,const一旦聲明變量,就必須立即初始化,不能留到以後賦值,但可以改變其屬性。
理解:let地址可變,const申明的變量指針所指的地址是不能改變的
const a={
a:1,
b:"dddd"
};
a.a=5;
a.c=10;
console.log(a.a);
console.log("c",a.c);
delete a.a;
console.log(a);
//運行結果
5
c 10
{ b: 'dddd', c: 10 }
2、三點式運算符
展開運算符(...)
數組展開:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 10, 20, 30];
// 這樣,arr2 就變成了[1, 2, 3, 10, 20, 30];
對象的展開:
// 這種方式在react中十分常用
const props = {
size: 1,
src: 'xxxx',
mode: 'si'
}
const { size, ...others } = props;
console.log(others)
const obj1 = {
a: 1,
b: 2,
c: 3
}
const obj2 = {
...obj1,
d: 4,
e: 5,
f: 6
}
// 結果類似於 const obj2 = Object.assign({}, obj1, {d: 4})
3、類對象Class
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
Point === Point.prototype.constructor // true
getter
get prop() {
return 'getter';
}
setter
set prop(value) {
console.log('setter: '+value);
}
extends
繼承
class NewObj extends Object{
constructor(){
super(...arguments);
}
}
var o = new NewObj({attr: true});
o.attr === true // false
4、數組
arr.push() 從後面添加元素,返回值爲添加完後的數組的長度
let arr = [1,2,3,4,5]
console.log(arr.push(5)) // 6
console.log(arr) // [1,2,3,4,5,5]
arr.pop() 從後面刪除元素,只能是一個,返回值是刪除的元素
let arr = [1,2,3,4,5]
console.log(arr.pop()) // 5
console.log(arr) //[1,2,3,4]
arr.concat() 連接兩個數組 返回值爲連接後的新數組
let arr = [1,2,3,4,5]
console.log(arr.concat([1,2])) // [1,2,3,4,5,1,2]
console.log(arr) // [1,2,3,4,5]
arr.forEach(value,index,array) 遍歷數組,無return
let array = [1,2,3,4];
array.forEach((item, index, array) => {
console.log(item);
});
arr.map(value,index,array) 映射數組(遍歷數組),有return 返回一個新數組
let array = [1, 2, 3, 4];
let temp = array.map((item, index, array) => {
return item * 10;
});
console.log(temp); // [10, 20, 30, 40];
console.log(array); // [1, 2, 3, 4]
// map 遍歷數組, 會返回一個新數組, 不會改變原來數組裏的內容
let temp2 = array.map(String); // 把數組裏的元素都轉成字符串
arr.filter(value,index,array)過濾數組,返回一個滿足要求的數組
let array = [1, 2, 3, 4];
let temp = array.filter((item, index, array) => {
return item > 3;
});
console.log(temp); // [4]
console.log(array); // [1, 2, 3, 4]
arr.every(value,index,array) 依據判斷條件,數組的元素是否全滿足,若滿足則返回ture
let array = [1, 2, 3, 4];
let bo = array.every((item, index, array) => {
return item > 2;
});
arr.some() 依據判斷條件,數組的元素是否有一個滿足,若有一個滿足則返回ture
let array = [1, 2, 3, 4];
let tmep = array.some((item, index, array) => {
return item > 1;
});