<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>數組增、刪方法(push()-unshift()-pop()和shift())</title> <!-- //添加 n.push();爲數組n添加值,添加的值位於數組n最後 n.unshift();爲數組n添加值,添加的值位於數組n最前面 -單獨打印添加值的代碼塊時,會輸出整個數組colors.length(即數組的長度) //刪除 n.pop();刪除數組n的最後一個值 n.shift();刪除數組n最前面的值 -單獨打印執行刪除的代碼塊時,會輸出被刪除的值 --> </head> <body> <script> // push var colors=["red","green","blue"]; var a=colors.push("black");//push添加的值位於colors最後面 console.log(colors); console.log(a);//單獨打印添加值的代碼塊時,會輸出數組colors.length(即數組的長度) //unshift var nums=[1,2,3,4,5]; var b=nums.unshift(-1,0);//unshift添加的值位於nums最前面 console.log(nums); console.log(b);//單獨打印添加值的代碼塊時,會輸出數組colors.length(即數組的長度) // pop var x=[1,2,3,4,5]; var q=x.pop();//pop刪除最後一個值:5 console.log(x); console.log(q);//單獨打印執行刪除的代碼塊時,會打印被刪除的值:5 //shift var y=[1,2,3,4,5]; var w=y.shift();//shift刪除最前面的值 console.log(y); console.log(w);//單獨打印執行刪除的代碼塊時,會打印被刪除的值:1 </script> </body> </html>