1数组


1.1方法列表

数组的常用方法如下:

  • concat: 链接两个或者更多数据,并返回结果。
  • every: 对数组中的每一项运行给定的函数,如果该函数对每一项都返回true,则返回true。
  • filter: 对数组中的每一项运行给定函数,返回改函数会返回true的项组成的数组。
  • forEach: 对数组中的每一项运行给定函数,这个方法没有返回值。
  • join: 将所有的数组元素链接成一个字符串。
  • indexOf: 返回第一个与给定参数相等的数组元素的索引,没有找到则返回-1。
  • lastIndexOf: 返回在数组中搜索到的与给定参数相等的元素的索引里最大的值。
  • map: 对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
  • reverse: 颠倒数组中元素的顺序,原先第一个元素现在变成最后一个,同样原先的最后一个元素变成现在的第一个。
  • slice: 传入索引值,将数组中对应索引范围内的元素作为新元素返回。
  • some: 对数组中的每一项运行给定函数,如果任一项返回true,则返回true。
  • sort: 按照字母顺序对数组排序,支持传入指定排序方法的函数作为参数。
  • toString: 将数组作为字符串返回。
  • valueOf: 和toString相似,将数组作为字符串返回。

1.2数组合并

concat方法可以向一个数组传递数组、对象或是元素。数组会按照该方法传入的参数顺序 连接指定数组。

    var zero = 0;
var positiveNumbers = [1,2,3];
var negativeNumbers = [-1,-2,-3];
var numbers = negativeNumbers.concat(zero,positiveNumbers);
console.log(numbers);//输出结果: [-1, -2, -3, 0, 1, 2, 3]

1.3迭代器函数

reduce方法接收一个函数作为参数,这个函数有四个参数:previousValue、currentValue、index和array。这个函数会返回一个将被叠加到累加器的 值,reduce方法停止执行后会返回这个累加器。如果要对一个数组中的所有元素求和,这就很有用了。

    var isEven = function(x){
return (x%2 == 0)?true:false;
}
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
//every方法会迭代数组中的每个元素,直到返回false。
var result = numbers.every(isEven);
console.log(result);//false
//some方法会迭代数组的每个元 素,直到函数返回true.
result = numbers.some(isEven);
console.log(result);//true
//forEach对每一项运行给定的函数,没有返回值
numbers.forEach(function(item,index){
console.log(item%2 == 0);
});
//map会迭代数组中的每个值,并且返回迭代结果
var myMap = numbers.map(isEven);
console.log(myMap);// [false, true, false, true, false, true, false, true, false, true, false, true, false, true, false]
//filter方法返回的新数组由使函数返回true的元素组成
var myFilter = numbers.filter(isEven);
console.log(myFilter);// [2, 4, 6, 8, 10, 12, 14]
//reduct函数
var myReduce = numbers.reduce(function(previous,current,index){
return previous + "" + current;
});
console.log(myReduce);//123456789101112131415

1.4排序

    var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
numbers.reverse();//[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
function compare(a,b){
if(a > b){
return 1;
}
if(a < b){
return -1;
}
return 0;
}
//sort函数使用
[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9].sort(compare); var friends = [{
name:'huang',
age:30
},{
name:'chengdu',
age:27
},{
name:'du',
age:31
}];
function comparePerson(a,b){
if(a.age > b.age){
return 1;
}
if(a.age < b.age){
return -1;
}
return 0;
}
console.log(friends.sort(comparePerson));// [Object { name="chengdu", age=27}, Object { name="huang", age=30}, Object { name="du", age=31}]
//搜索
numbers.push(10);
console.log(numbers.indexOf(10));//5
console.log(numbers.lastIndexOf(10));//15
var numbersString = numbers.join('-');
console.log(numbersString);//15-14-13-12-11-10-9-8-7-6-5-4-3-2-1-10

2栈


2.1栈的创建

对于一个栈,我们需要实现添加、删除元素、获取栈顶元素、已经是否为空,栈的长度、清除元素等几个基本操作。下面是基本定义。

    function Stack(){
this.items = [];
}
Stack.prototype = {
constructor:Stack,
push:function(element){
this.items.push(element);
},
pop:function(){
return this.items.pop();
},
peek:function(){
return this.items[this.items.length - 1];
},
isEmpty:function(){
return this.items.length == 0;
},
clear:function(){
this.items = [];
},
size:function(){
return this.items.length;
},
print:function(){
console.log(this.items.toString());
}
}

2.2栈的基本使用

栈的基本操作。

    var stack = new Stack();
console.log(stack.isEmpty());//true
stack.push(5);
stack.push(8);
console.log(stack.peek());//8
stack.push(11);
console.log(stack.size());//3
console.log(stack.isEmpty());
stack.push(15);
stack.pop();
stack.pop();
console.log(stack.size());//2
console.log(stack.print());//5,8

通过栈实现对正整数的二进制转换。

    function divideBy2(decNumber){
var decStack = new Stack();
var rem;
var decString = '';
while(decNumber > 0){
rem = decNumber%2;
decStack.push(rem);
decNumber = Math.floor(decNumber/2);
}
while(!decStack.isEmpty()){
decString += decStack.pop().toString();
}
return decString;
}
console.log(divideBy2(10));//1010

3队列


3.1队列的创建

队列是遵循FIFO(First In First Out,先进先出,也称为先来先服务)原则的一组有序的项。队列在尾部添加新元素,并从顶部移除元素。最新添加的元素必须排在队列的末尾。队列要实现的操作基本和栈一样,只不过栈是FILO(先进后出)。

    function Queue(){
this.items = [];
}
Queue.prototype = {
constructor:Queue,
enqueue:function(elements){
this.items.push(elements);
},
dequeue:function(){
return this.items.shift();
},
front:function(){
return this.items[0];
},
isEmpty:function(){
return this.items.length == 0;
},
size:function(){
return this.items.length;
},
clear:function(){
this.items = [];
},
print:function(){
console.log(this.items.toString());
}
}

队列的基本使用

    var queue = new Queue();
console.log(queue.isEmpty());//true
queue.enqueue('huang');
queue.enqueue('cheng');
console.log(queue.print());//huang,cheng
console.log(queue.size());//2
console.log(queue.isEmpty());//false
queue.enqueue('du');
console.log(queue.dequeue());//huang
console.log(queue.print());//cheng,du

3.2 优先队列

元素的添加和移除是基于优先级的。实现一个优先队列,有两种选项:设置优先级,然后在正确的位置添加元素;或者用入列操 作添加元素,然后按照优先级移除它们。 我们在这里实现的优先队列称为最小优先队列,因为优先级的值较小的元素被放置在队列最 前面(1代表更高的优先级)。最大优先队列则与之相反,把优先级的值较大的元素放置在队列最 前面。

3.2.1 优先队列的定义

我们在这里使用组合继承的方式继承自Queue队列。

    function PriorityQueue(){
Queue.call(this);
};
PriorityQueue.prototype = new Queue();
PriorityQueue.prototype.constructer = PriorityQueue;
PriorityQueue.prototype.enqueue = function(element,priority){
function QueueElement(tempelement,temppriority){
this.element = tempelement;
this.priority = temppriority;
}
var queueElement = new QueueElement(element,priority);
if(this.isEmpty()){
this.items.push(queueElement);
}else{
var added = false;
for(var i = 0; i < this.items.length;i++){
if(this.items[i].priority > queueElement.priority){
this.items.splice(i,0,queueElement);
added = true;
break;
}
}
if(!added){
this.items.push(queueElement);
}
} }
//这个方法可以用Queue的默认实现
PriorityQueue.prototype.print = function(){
var result ='';
for(var i = 0; i < this.items.length;i++){
result += JSON.stringify(this.items[i]);
}
return result;
}

3.2.1 优先队列的基本使用

    var priorityQueue = new PriorityQueue();
priorityQueue.enqueue("cheng", 2);
priorityQueue.enqueue("du", 3);
priorityQueue.enqueue("huang", 1);
console.log(priorityQueue.print());//{"element":"huang","priority":1}{"element":"cheng","priority":2}{"element":"du","priority":3}
console.log(priorityQueue.size());//3
console.log(priorityQueue.dequeue());//{ element="huang", priority=1}
console.log(priorityQueue.size());//2

3链表


数组的大小是固定的,从数组的起点或中间插入 或移除项的成本很高,因为需要移动元素(尽管我们已经学过的JavaScript的Array类方法可以帮 我们做这些事,但背后的情况同样是这样)。链表存储有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。每个 元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或链接)组成。

相对于传统的数组,链表的一个好处在于,添加或移除元素的时候不需要移动其他元素。然 而,链表需要使用指针,因此实现链表时需要额外注意。数组的另一个细节是可以直接访问任何 位置的任何元素,而要想访问链表中间的一个元素,需要从起点(表头)开始迭代列表直到找到 所需的元素

3.1.1链表的创建

我们使用动态原型模式来创建一个链表。列表最后一个节点的下一个元素始终是null。

    function LinkedList(){
function Node(element){
this.element = element;
this.next = null;
}
this.head = null;
this.length = 0;
//通过对一个方法append判断就可以知道是否设置了prototype
if((typeof this.append !== 'function')&&(typeof this.append !== 'string')){
//添加元素
LinkedList.prototype.append = function(element){
var node = new Node(element);
var current;
if(this.head === null){
this.head = node;
}else{
current = this.head;
while(current.next !== null){
current = current.next;
}
current.next = node;
}
this.length++;
};
//插入元素,成功true,失败false
LinkedList.prototype.insert = function(position,element){
if(position > -1 && position < this.length){
var current = this.head;
var previous;
var index = 0;
var node = new Node(element);
if(position == 0){
node.next = current;
this.head = node;
}else{
while(index++ < position){
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
}
this.length++;
return true;
}else{
return false;
}
};
//根据位置删除指定元素,成功 返回元素, 失败 返回null
LinkedList.prototype.removeAt = function(position){
if(position > -1 && position < this.length){
var current = this.head;
var previous = null;
var index = 0;
if(position == 0){
this.head = current.next;
}else{
while(index++ < position){
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length--;
return current.element;
}else{
return null;
}
};
//根据元素删除指定元素,成功 返回元素, 失败 返回null
LinkedList.prototype.remove = function(element){
var index = this.indexOf(element);
return this.removeAt(index);
};
//返回给定元素的索引,如果没有则返回-1
LinkedList.prototype.indexOf = function(element){
var current = this.head;
var index = 0;
while(current){
if(current.element === element){
return index;
}
index++;
current = current.next;
}
return -1;
};
LinkedList.prototype.isEmpty = function(){
return this.length === 0;
};
LinkedList.prototype.size = function(){
return this.length;
};
LinkedList.prototype.toString = function(){
var string = '';
var current = this.head;
while(current){
string += current.element;
current = current.next;
}
return string;
};
LinkedList.prototype.getHead = function(){
return this.head;
};
}
}

3.1.2链表的基本使用

    var linkedList = new LinkedList();
console.log(linkedList.isEmpty());//true;
linkedList.append('huang');
linkedList.append('du')
linkedList.insert(1,'cheng');
console.log(linkedList.toString());//huangchengdu
console.log(linkedList.indexOf('du'));//2
console.log(linkedList.size());//3
console.log(linkedList.removeAt(2));//du
console.log(linkedList.toString());//huangcheng

3.2.1双向链表的创建

链表有多种不同的类型,这一节介绍双向链表。双向链表和普通链表的区别在于,在链表中, 一个节点只有链向下一个节点的链接,而在双向链表中,链接是双向的:一个链向下一个元素, 另一个链向前一个元素。

双向链表和链表的区别就是有一个tail属性,所以必须重写insert、append、removeAt方法。每个节点对应的Node也多了一个prev属性。

   //寄生组合式继承实现,详见javascript高级程序设计第七章
function inheritPrototype(subType, superType) {
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function DoublyLinkedList() {
function Node(element) {
this.element = element;
this.next = null;
this.prev = null;
}
this.tail = null;
LinkedList.call(this);
//与LinkedList不同的方法自己实现。
this.insert = function(position, element) {
if (position > -1 && position <= this.length) {
var node = new Node(element);
var current = this.head;
var previous;
var index = 0;
if (position === 0) {
if (!this.head) {
this.head = node;
this.tail = node;
} else {
node.next = current;
current.prev = node;
this.head = node;
}
} else if (position == this.length) {
current = this.tail;
current.next = node;
node.prev = current;
this.tail = node;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = node;
node.next = current;
current.prev = node;
node.prev = previous;
}
this.length++;
return true;
} else {
return false;
}
};
this.append = function(element) {
var node = new Node(element);
var current;
if (this.head === null) {
this.head = node;
this.tail = node;
} else {
current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
node.prev = current;
this.tail = node;
}
this.length++;
};
this.removeAt = function(position) {
if (position > -1 && position < this.length) {
var current = this.head;
var previous;
var index = 0;
if (position === 0) {
this.head = current.next;
if (this.length === 1) {
this.tail = null;
} else {
this.head.prev = null;
}
} else if (position === (this.length - 1)) {
current = this.tail;
this.tail = current.prev;
this.tail.next = null;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
current.next.prev = previous;
}
this.length--;
return current.element;
} else {
return false;
}
};
}
inheritPrototype(DoublyLinkedList, LinkedList);

3.2.2双向链表的基本使用

    var doublyList = new DoublyLinkedList();
console.log(doublyList.isEmpty()); //true;
doublyList.append('huang');
doublyList.append('du')
doublyList.insert(1, 'cheng');
console.log(doublyList.toString()); //huangchengdu
console.log(doublyList.indexOf('du')); //2
console.log(doublyList.size()); //3
console.log(doublyList.removeAt(2)); //du
console.log(doublyList.toString()); //huangcheng

3.2.3 循环链表

循环链表可以像链表一样只有单向引用,也可以像双向链表一样有双向引用。循环链表和链 表之间唯一的区别在于,最后一个元素指向下一个元素的指针(tail.next)不是引用null, 而是指向第一个元素(head)。双向循环链表有指向head元素的tail.next,和指向tail元素的head.prev。

JavaScript 的数据结构与算法的更多相关文章

  1. javascript实现数据结构与算法系列:栈 -- 顺序存储表示和链式表示及示例

    栈(Stack)是限定仅在表尾进行插入或删除操作的线性表.表尾为栈顶(top),表头为栈底(bottom),不含元素的空表为空栈. 栈又称为后进先出(last in first out)的线性表. 堆 ...

  2. JavaScript 版数据结构与算法(二)队列

    今天,我们要讲的是数据结构与算法中的队列. 队列简介 队列是什么?队列是一种先进先出(FIFO)的数据结构.队列有什么用呢?队列通常用来描述算法或生活中的一些先进先出的场景,比如: 在图的广度优先遍历 ...

  3. 第一章:javascript: 数据结构与算法

    在前端工程师中,常常有一种声音,我们为什么要学数据结构与算法,没有数据结构与算法,我们一样很好的完成工作.实际上,算法是一个宽泛的概念,我们写的任何程序都可以称为算法,甚至往冰箱里放大象,也要通过开门 ...

  4. JavaScript 版数据结构与算法(一)栈

    今天,我们要讲的是数据结构与算法中的栈. 栈的简介 栈是什么?栈是一个后进先出(LIFO)的数据结构.栈有啥作用?栈可以模拟算法或生活中的一些后进先出的场景,比如: 十进制转二进制,你需要将余数倒序输 ...

  5. JavaScript 版数据结构与算法(三)链表

    今天,我们要讲的是数据结构与算法中的链表. 链表简介 链表是什么?链表是一种动态的数据结构,这意味着我们可以任意增删元素,它会按需扩容.为何要使用链表?下面列举一些链表的用途: 因为数组的存储有缺陷: ...

  6. JavaScript 版数据结构与算法(四)集合

    今天,我们要讲的是数据结构与算法中的集合. 集合简介 什么是集合?与栈.队列.链表这些顺序数据结构不同,集合是一种无序且唯一的数据结构.集合有什么用?在 Python 中,我经常使用集合来给数组去重: ...

  7. JavaScript的数据结构和算法

    所有JavaScript对象都有hasOwnProperty(value)的方法,用来返回一个表明对象是不是具有这个value Key值属性的布尔值. javaScript的方法 具有delete的方 ...

  8. javascript实现数据结构与算法系列:循环链表与双向链表

    循环链表(circular linked list) 是另一种形式的链式存储结构.它的特点是表中最后一个结点的指针域指向头结点,整个表形成一个环. 循环链表的操作和线性链表基本一致,仅有细微差别. w ...

  9. javascript实现数据结构与算法系列

    1.线性表(Linear list) 线性表--简单示例及线性表的顺序表示和实现 线性表--线性链表(链式存储结构) 线性表的静态单链表存储结构 循环链表与双向链表 功能完整的线性链表 线性链表的例子 ...

随机推荐

  1. .NET CORE AutoMapper使用

    1.通过nuget安装AutoMapper,版本是7.0.1, 安装AutoMapper.Extensions.Microsoft.DependencyInjection  版本是4.0.1 不是以上 ...

  2. Java连载69-接受输入、用数组模拟栈

    一.编写一个酒店管理系统 1.直接上代码 package com.bjpowernode.java_learning; ​ public class D69_1_ { //编写一个程序模拟酒店的管理系 ...

  3. php序列化(serialize)和反序列化(unserialize)函数

    用法:serialize().unserialize() 适用情境:serialize()返回字符串,此字符串包含了表示value的字节流,可以存储于任何地方.这有利于存储或传递 PHP 的值,同时不 ...

  4. 吴裕雄--天生自然C++语言学习笔记:C++ 变量作用域

    作用域是程序的一个区域,一般来说有三个地方可以定义变量: 在函数或一个代码块内部声明的变量,称为局部变量. 在函数参数的定义中声明的变量,称为形式参数. 在所有函数外部声明的变量,称为全局变量. 局部 ...

  5. 吴裕雄--天生自然TensorFlow2教程:填充与复制

    import tensorflow as tf a = tf.reshape(tf.range(9), [3, 3]) a tf.pad(a, [[0, 0], [0, 0]]) tf.pad(a, ...

  6. decltype关键字

    decltype用于编译时类型推导,是以一个普通表达式作为参数,返回该表达式的类型,而且decltype并不会对表达式进行求值. decltype的用法: //推导出表达式类型 ; decltype( ...

  7. tensorflow---darknet53

    #! /usr/bin/env python# coding=utf-8#=============================================================== ...

  8. h5-多列布局

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. java.lang.SecurityException: Permission denied (missing INTERNET permission?)

    ndroid app里试图用HttpUrlConnection获取网络连接,忘记在AndroidManifest清单文件里声明需要用到Internet的权限,运行时报此错误. 解决方法 在Androi ...

  10. 学会拒绝,是一种智慧——OO电梯章节优化框架的思考

    在本章的三次作业里,每次作业我都有一个主题,分别是:托盘型共享数据.单步电梯运行优化.多部电梯运行优化,因而电梯优化实际是第二.三次作业.虽然后两次作业从性能分上看做得还不错,但阅读其他大佬博客,我深 ...