首页 > 网站 > WEB开发 > 正文

【数组】数组的增改查

2024-04-27 15:15:22
字体:
来源:转载
供稿:网友

1、给原数组中 新增

用到 push 改变原数组的长度并返回新的长度,新元素添加在原数组的末尾

<doctype><html> <head>元素新增数组</head> <body> <div id="dem">点击会给原素组末尾新增元素个数</div> <button onclick="funct()">点击</button> <script type="text/javascript"> var app = ["001","002","002"]; function funct(){ app.push("003","0005"); var demo = document.getElementById("dem"); demo.innerHTML = app; } </script> </body></html>

unshift 在原数组的开头添加一个新的元素或是更多的元素并返回新的长度。

<!doctype html ><html> <head></head> <body> <div id="dem">点击会给原素组前面新增元素个数</div> <button onclick="funct()">点击</button> <script type="text/Javascript"> var app = ["001","002","002"]; function funct(){ app.unshift("003","0005"); var demo = document.getElementById("dem"); demo.innerHTML = app; } </script> </body><html>

2、移除 数组最后一个元素

pop() 并返回删除的数组

<!doctype html><html> <head> </head> <body> <div id="demo">移除最后一个元素</div> <button onclick="fun()"></button> <script type="text/javascript" charset="utf-8"> var apple = ["001","002","003"]; function fun(){ apple.pop(); var demo = document.getElementsById("demo"); demo.innerHtml = apple; } </script> </body></html>

3.数组中的splice() 用于插入替换 和删除

会改变原数组

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>数组里面的push和pop </title> <script type="text/javascript" src="../js/jquery.min.js"></script></head><body> <div id="demo02">单击删除bing并tihuan一个元素</div> <button onclick="fun01()">删除</button> <script type="text/javascript"> var apple = ["Sunday","Monday","Tuesday","Wednesday"]; function fun01(){ apple.splice(1,2,"2222"); //从Moday下标开始删除两个,替换为"2222" var demo = document.getElementById("demo02"); demo.innerHTML = apple; } </script></body></html>

4.js的加载方式

通过scrpit标签加载在head 或者是 body的外部或者是内部 通过元素的事件名加载函数

5.switch case用法

function fun(){ var num = "01"; switch (num){ case "01":console.log("星期一"); //代码块 break; case "02":fun01(); break; default:console.log("星期八"); } }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表