JavaScript 基础数组方法
一些基本的 JavaScript 数组方法是 −
方法 | 描述 |
---|---|
Array.push() | 向数组的末尾添加元素。 |
Array.pop() | 从数组的末尾移除元素。 |
Array.unshift() | 向数组的开头添加元素 |
Array.shift() | 从数组的开头移除元素。 |
Array.splice() | 从 splice 添加或移除元素 |
以下是基本数组方法的代码 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample, .result { font-size: 18px; font-weight: 500; color: red; } .result { color: blueviolet; } </style> </head> <body> <h1>JavaScript Basic array methods</h1> <div class="sample">arr =</div> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to apply the array methods on the above array</h3> <script> let resultEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let arr = ["A", "B", 1, 2, 3, 5]; sampleEle.innerHTML += arr; document.querySelector(".Btn").addEventListener("click", () => { arr.pop(); resultEle.innerHTML += "arr.pop() = " + arr + "<br>"; arr.push(22); resultEle.innerHTML += "arr.push(22) = " + arr + "<br>"; arr.shift(); resultEle.innerHTML += "arr.shift() = " + arr + "<br>"; arr.unshift(); resultEle.innerHTML += "arr.unshift(55) = " + arr + "<br>"; arr.splice(3, 0, "D", "E", "F"); resultEle.innerHTML += 'Array.splice(3,0,"D","E","F") = ' + arr; }); </script> </body> </html>
输出
单击‘点击这里’按钮 −
广告