PHP前端开发

数据结构与算法第 0 天

百变鹏仔 3天前 #JavaScript
文章标签 数据结构

第 0 天

基本数据结构

我们将看到 javascript 中的所有代码示例,但这些概念与语言无关

  1. 数组

数组是元素的集合,通常具有相同类型,存储在连续的内存位置。

数组作为书籍列表:
想象一下,您有一个书架,可容纳特定数量的书籍。书架上的每个槽位就像数组中的一个索引,而每本书就像存储在该索引处的元素。

主要特征:

索引:每个元素都可以通过其索引进行访问(从 0 开始或从 1 开始,具体取决于语言)。

const fruit  = ['banana','apple','grape', 'pineapple']console.log(fruit[0]) //  banana is accessed 0 indexconsole.log(fruit[3]) // pineapple is accessed 3 index

固定大小:一旦声明,数组的大小就不能改变(静态数组)。
在具有静态数组的语言中,当声明数组时,必须在创建时指定其大小。这意味着,如果你声明一个大小为5的数组,那么它只能存储5个元素,并且以后不能更改大小。一旦数组满了,你就不能添加更多元素,也不能缩小它。

但是,javascript 数组本质上是动态的,因此在大多数情况下没有这种固定大小的限制。但要从概念上理解固定大小数组,请想象一下 javascript 数组是否无法增长或缩小。

let fixedarray = new array(3); // array with a fixed size of 3fixedarray[0] = 'apple';fixedarray[1] = 'banana';fixedarray[2] = 'cherry';// now if you try to add another item:fixedarray[3] = 'date'; // this would throw an error or overwrite an existing element (hypothetically)console.log(fixedarray) // [ 'apple', 'banana', 'cherry', 'date' ]

随机访问:您可以使用其索引直接访问任何元素。

const fruit  = ['Banana','Apple','Grape', 'Pineapple']console.log(fruit[0]) // index 0 is the Banana console.log(fruit[3]) // index 3 is the Pineapple 

优点:

缺点: