JavaScript數(shù)據(jù)結構筆記 - 數(shù)組

靜態(tài)數(shù)組(Static Array)vs 動態(tài)數(shù)組(Dynamic Array)

靜態(tài)數(shù)組是一個固定長度的數(shù)組,內含n個可索引的(indexable)元素,索引范圍是[0, n-1]。

相反,動態(tài)數(shù)組的長度不固定。

復雜度

JavaScript數(shù)據(jù)結構筆記 - 數(shù)組

*靜態(tài)數(shù)組由于長度固定,無法進行插入、結尾插入、刪除操作。

手寫動態(tài)數(shù)組

數(shù)據(jù)結構

const fruit = {
    length: 4,
    data: {
        0: "蘋果",
        1: "香蕉",
        2: "桃子",
        3: "菠蘿"
    }
}

實現(xiàn)

// 定義MyArray類
class MyArray {
  // 構造器
  constructor() {
    // length屬性保存數(shù)組的長度
    this.length = 0;
    // data屬性保存每個元素
    this.data = {};
  }
  // push或append函數(shù),在數(shù)組結尾插入新元素
  push(element) {
    this.data[this.length] = element;
    this.length++;
    return this.data;
  }
  // insertAt函數(shù),在給定位置插入新元素
  insertAt(item, index) {
    for (let i = this.length; i >= index; i--) {
      this.data[i] = this.data[i - 1];
    }
    this.data[index] = item;
    this.length++;
    return this.data;
  }
  // deleteAt函數(shù),刪除給定位置的元素
  deleteAt(index) {
    for (let i = index; i < this.length - 1; i++) {
      this.data[i] = this.data[i + 1];
    }
    delete this.data[this.length - 1];
    this.length--;
    return this.data;
  }
  // getElementAtIndex函數(shù),返回給定位置的元素
  getElementAtIndex(index) {
    return this.data[index];
  }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
禁止轉載,如需轉載請通過簡信或評論聯(lián)系作者。

相關閱讀更多精彩內容

友情鏈接更多精彩內容