在 JavaScript 对象的数组上使用数组的方法?
以下是如何在 JavaScript 对象的数组上使用 array 方法的代码 −
示例
<!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; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Using methods of array on array of JavaScript objects</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click the above button to apply array methods on array of objects</h3> <script> let BtnEle = document.querySelector(".Btn"); let arr = [ { name: "Rohan", age: 22, rollNo: "A12", }, { name: "Mohit", age: 12, rollNo: "B21", }, { name: "Shawn", age: 18, rollNo: "C43", }, ]; BtnEle.addEventListener("click", () => { arr.pop(); arr.push({ name: "Michael", age: 17, rollNo: "AC9" }); arr.splice(1, 1); console.log(arr); }); </script> </body> </html>
输出
上面的代码将生成以下输出 −
单击“单击此处”按钮并检查控制台中的输出 −
广告