1 function Stack() { 2 this.dataStore = []; 3 this.top = 0; //指向栈顶的位置 4 this.push = push; 5 this.pop = pop; 6 this.peek = peek; 7 this.clear = clear; 8 this.length = length; 9 10 function push(element) {11 this.dataStore[this.top++] = element; //先赋值后++12 }13 14 function peek() {15 return this.dataStore[this.top - 1];16 }17 18 function pop() {19 return this.dataStore[--this.top]; //先--运算20 }21 22 function clear() {23 this.top = 0;24 }25 26 function length() {27 return this.top;28 }29 }30 31 var s = new Stack(); 32 s.push("David"); 33 s.push("Raymond"); 34 s.push("Bryan"); 35 console.log(s);36 console.log("length: " + s.length());
注意:
这样的一步操作arr[i++]="ddd";----》这里的执行顺序是:先执行赋值后进行的++运算
等价于下面的两布操作:
arr[i] = "ddd";
i++;
//这样写才是先执行++运算
arr[++i]="ddd";