JS-对列的简单操作

JavaScript02

JS-对列的简单操作,第1张

我们先来看一看对列的常见操作

下面实现对列的常见操作及验证

<!doctype html>

<html lang="en">

    <meta charset="UTF-8">

    <meta name="viewport"

          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Queue的使用!

<!--    封装队列类-用数组实现-->

function Queue(){

//属性

        this.items=[]

//    方法

    //    1.将元素插入到队列中

        Queue.prototype.enqueue=(elements)=>{

this.items.push(elements)

}

//    2.从队列中删除首要元素

        Queue.prototype.dequeue=()=>{

//这是js中的shift删除方法,用于把数组中第一个元素的值从其中删除,并返回第一个元素的值

            return this.items.shift()

}

//    3.查看当前的元素

        Queue.prototype.front=()=>{

return this.items[0]

}

//    4.查看队列是否为空

        Queue.prototype.isEmpty=()=>{

return this.items.length===0

        }

//    5.查看队列中元素的个数

        Queue.prototype.size=()=>{

return this.items.length

        }

//    6.toSting的方法

        Queue.prototype.toString=()=>{

let resultString=''

            for (let i=0i

resultString +=this.items[i]+' '

            }

return resultString

        }

}

//    使用队列

    let queue=new Queue()

//验证,将元素加入到队列中

queue.enqueue('abc')

queue.enqueue('cba')

queue.enqueue('nba')

queue.enqueue('cxw')

alert(queue)

//从队列中删除元素

queue.dequeue()

alert(queue)

queue.dequeue()

alert(queue)

//验证front

alert(queue.front())

//、验证其他方法

alert(queue.isEmpty())

alert(queue.size())

</html>

验证结果

<!doctype html>

<html lang="en">

    <meta charset="UTF-8">

    <meta name="viewport"

          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

  function Stack(){

//栈中的属性

      this.items=[]

//    栈的相关操作

  //  1.将元素压入栈,两种方法!第二种方法好啊!,第一种方法是对某个实例添加了方法,第二种方法是对某个类添加了方法!共享!

  //    this.push=function (){}

      Stack.prototype.push= (element)=>{

this.items.push(element)

}

// 2.将栈中的元素取出来

      Stack.prototype.pop=()=>{

return this.items.pop()

}

//    3.查看栈中的元素

      Stack.prototype.peek=()=>{

return this.items[this.items.length-1]

}

//    4.判断栈是否空

      Stack.prototype.isEmpty=()=>{

return  this.items.length===0

      }

//    5.获取栈中元素的个数

      Stack.prototype.size=()=>{

return this.items.length

      }

//    6.toString的方法

      Stack.prototype.toString=()=>{

//    20 10 12 8 7

          let resultString=''

          for (let i=0i

resultString +=this.items[i]+' '

          }

return resultString

}

}

//  栈的使用

//  验证!

  let s=new Stack()

s.push(20)

s.push(10)

s.push(100)

s.push(77)

alert(s)

s.pop()

s.pop()

alert(s)

alert(s.peek())

alert(s.isEmpty())

alert(s.size())

</html>

结果显示:

成功实现!