web前端學習筆記(1)

9月5日

array.push(...newArray)    // 往數組插入數組

// 交換a和b的值
// ES6寫法
var a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b);    // 2 1

// Babel轉換成ES5後
var a = 1,
    b = 2;
var _ref = [b, a];
a = _ref[0];
b = _ref[1];
console.log(a, b);    // 2 1

// 獲取某個元素相對於瀏覽器窗口的位置
var domRect = element.getBoundingClientRect();

// 刪除數組index一、index2位置上的數,並返回裁剪部分的新數組
_.pullAt(array, [index1, index2]);

9月6日

Promise對象

  • Promise有三種狀態:pending(進行中)、fulfilled(已成功)和rejected(已失敗)。並且狀態一旦改變,就沒法再次改變。
  • Promise新建後會當即執行。

好比:es6

function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms, 'done');
  });
}

timeout(100).then((value) => {
  console.log(value);
});

上面代碼中,timeout方法返回一個Promise實例,表示一段時間之後纔會發生的結果。過了指定的時間(ms參數)之後,Promise實例的狀態變爲resolved,就會觸發then方法綁定的回調函數。數組

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('resolved.');
});

console.log('Hi!');

// Promise
// Hi!
// resolved
new Promise((resolve, reject) => {
  resolve(1);
  console.log(2);
}).then(r => {
  console.log(r);
});

// 2
// 1

上面代碼中,調用resolve(1)之後,後面的console.log(2)仍是會執行,而且會首先打印出來。這是由於當即 resolved 的 Promise 是在本輪事件循環的末尾執行,老是晚於本輪循環的同步任務。promise

var promise = new Promise(function (resolve, reject) {
  resolve('ok');
  setTimeout(function () { throw new Error('test') }, 0)
});
promise.then(function (value) { console.log(value) });
// ok
// Uncaught Error: test

Promise.resolve()是在本輪「事件循環」的結束時執行,而不是在下一輪「事件循環」的開始。瀏覽器

setTimeout(function () {
  console.log('three');
}, 0);

Promise.resolve().then(function () {
  console.log('two');
});

console.log('one');

// one
// two
// three

上面代碼中,setTimeout(fn, 0)在下一輪「事件循環」開始時執行,Promise.resolve()在本輪「事件循環」結束時執行,console.log('one')則是當即執行,所以最早輸出。dom

字符串

  • includes():返回布爾值,表示是否找到了參數字符串。
  • startsWith():返回布爾值,表示參數字符串是否在原字符串的頭部。
  • endsWith():返回布爾值,表示參數字符串是否在原字符串的尾部。
  • repeat():返回一個新的字符串,表示將原字符串重複n次。若是參數是小數,則會被取整。
  • padStart()、padEnd():字符串補全長度的功能。若是某個字符串不夠長度,會在頭部或尾部補全。padStart()用於頭部補全,padEnd()用於尾部補全。

includes()startsWith()endsWith()都支持傳入第二個參數,傳入開始搜索的位置。padStart()padEnd()函數

JS數組去重黑魔法

使用數組新建一個Set對象,而後把它轉換成數組code

var array = [1, 2, 3, 4, 1, 2, 3, 4];

console.log([...new Set(array)]);    // [1, 2, 3, 4]

console.log(Array.from(new Set(array)));    // [1, 2, 3, 4]

文章出處:阮一峯ES6入門對象

相關文章
相關標籤/搜索