JavaScript30 - 4.Array Cardio 1

東岸往事·發表於2016-12-20

❤️ javascript30是一系列的視訊教程,旨在30天編寫30個前端小專案。 這些專案不需要使用其他lib,不需要編譯,不需要模板,迴歸最純真的JavaScript;

? ? ?

? 這是這個系列的第4篇

專案程式碼同步更新在男同交友網

內容簡介

熟悉並掌握JavaScript中Array的使用,以及一些開發的小技巧;

本期先講一部分,剩餘的在第7期中繼續完成;

知識點

JS

實踐

Array 的屬性

length

  • length: 值是一個 0 到 232-1 的整數。

用處:

  • 返回陣列的長度
  • 將陣列的長度指定為X, 進行陣列截斷若 X=0 則表示陣列為空(清空陣列)

?:

const length_test = [1, 3, 55, 66]
console.log(length_test.length)

length_test.length = 2
console.log(length_test)複製程式碼

這裡附平時常用的清空陣列的操作:

// 清空陣列
let empty_test = [1,2,3,4];  

// 1.length = 0
empty_test.length = 0

// 2. empty_test = []
empty_test = []

// 3. splice
empty_test.splice(0)複製程式碼

效率最好的是第二種,但是推薦使用第一種; 因為第二種新建了記憶體

prototype

......大部分的方法都是原型鏈上的方法。 具體的每個方法會在後續一一實踐;

console.log(Array.prototype)複製程式碼

JavaScript30 - 4.Array Cardio 1

Array 的靜態方法(類方法)

靜態方法是指那些不需要對類進行例項化,使用類名就可以直接訪問的方法,需要注意的是靜態方法不能被例項化的物件呼叫。靜態方法經常用來作為工具函式。 --MDN

  • Array.isArray() : 如果物件是 Array 返回true,否則false。
// Array.isArray()
const type_test = [];
const type_test1 = {};
console.log('type_test type is array? : ', Array.isArray(type_test))
console.log('type_test1 type is array? : ', Array.isArray(type_test1))複製程式碼

那麼如果遇到不支援ES6語法的瀏覽器呢?
這裡實現一種更加健壯的Array檢測方法

function isArray(value){  
  if (typeof Array.isArray === "function") {  
      return Array.isArray(value);      
  }else{  
      return Object.prototype.toString.call(value) === "[object Array]";      
  }  
}複製程式碼
  • (ES6) Array.from() : 可以將一個類陣列物件或可遍歷物件轉換成真正的陣列。

類陣列物件(擁有一個 length 屬性和若干索引屬性的任意物件)
可遍歷物件(你可以從它身上迭代出若干個元素的物件,比如有 Map 和 Set 等)

語法:

Array.from(arrayLike[, mapFn[, thisArg]])複製程式碼
  • arrayLike: 想要轉換成真實陣列的類陣列物件或可遍歷物件。
  • mapFn: 可選引數,如果指定了該引數,則最後生成的陣列會經過該函式的加工處理後再返回。
  • thisArg:可選引數,執行 mapFn 函式時 this 的值。
// 將可迭代物件(Set 物件)轉換成陣列
Array.from(new Set(["foo", window])); 

// 使用 map 函式轉換陣列元素
Array.from([1, 2, 3], x => x + x);      // [2, 4, 6]

// 生成一個數字序列
Array.from({length:5}, (v, k) => k);    // [0, 1, 2, 3, 4]複製程式碼

tips: 發現了一個小玩意

// 實現字串反轉
let str = 'abcd'
Array.from(str).reverse().join('')複製程式碼
  • Array.of(): 將它的任意型別的多個引數放在一個陣列裡並返回
    語法:
Array.of(element0[, element1[, ...[, elementN]]])複製程式碼

?:

Array.of(1);         // [1]
Array.of(1, 2, 3);   // [1, 2, 3]
Array.of(undefined); // [undefined]複製程式碼

對於不支援的瀏覽器,可以這樣做:

if (!Array.of) {
  Array.of = function() {
    return Array.prototype.slice.call(arguments);
  };
}複製程式碼

Array 物件方法

棧和佇列.pop,.push,.shift和.unshift

  • push: 法新增一個或多個元素到陣列的末尾(改變原陣列),並返回陣列新的長度(length 屬性值)
let sports = ["soccer", "baseball"];
let total = sports.push("football", "swimming");

console.log(sports); // ["soccer", "baseball", "football", "swimming"]
console.log(total);  // 4複製程式碼

tips: 用Array.pus().apply(arr1,arr2)來替代建立一個新陣列。這種方法不是用來建立一個新的陣列,其只是將第一個第二個陣列合並在一起,同時減少記憶體的使用:

let array1 = [1,2,3];
let array2 = [4,5,6];
console.log(array1.push.apply(array1, array2));複製程式碼
  • pop: 刪除一個陣列中的最後的一個元素,並且返回這個元素
let colors = ['red', 'yellow', 'white'];

console.log(colors);

let target = myFish.pop();

console.log(colors);
console.log(target);複製程式碼

.pop方法和.push成對使用,它返回陣列的末尾元素並將元素從陣列移除。如果陣列為空,返回void 0(undefined)。使用.push和.pop我們能輕易模擬出LIFO(後進先出或先進後出)棧 -- 有趣的JavaScript原生陣列函式

簡易棧(Stack)的實現:

function Stack () {
    this._stack = []
}

Stack.prototype.next = function () {
    return this._stack.pop()
}

Stack.prototype.add = function () {
    return this._stack.push.apply(this._stack, arguments)
}

stack = new Stack()
stack.add(1,2,3)

stack.next()複製程式碼
  • shift: 刪除陣列的第一個元素,並返回這個元素。該方法會改變陣列的長度

    shift 方法移除索引為 0 的元素(即第一個元素),並返回被移除的元素,其他元素的索引值隨之減 1。如果 length 屬性的值為 0 (長度為 0),則返回 void 0(undefined)

// shift
let colors2 = ['red', 'yellow', 'white'];

console.log(colors2);

let target = colors2.shift();

console.log(colors2);
console.log(target2);複製程式碼
  • unshift: 在陣列的開頭新增一個或者多個元素,並返回陣列新的 length 值
let arr = [1, 2];

arr.unshift(0); //result of call is 3, the new array length
//arr is [0, 1, 2]複製程式碼

用.unshift 和 .shift模擬FIFO(先進先出)佇列(Queue)

function Queue () {
    this._queue = []
}

Queue.prototype.next = function () {
    return this._queue.shift()
}

Queue.prototype.add = function () {
    return this._queue.unshift.apply(this._queue, arguments)
}

queue = new Queue()
queue.add(1,2,3)

queue.next()複製程式碼

本文對你有幫助?歡迎掃碼加入前端學習小組微信群:

JavaScript30 - 4.Array Cardio 1

相關文章