1 slice选取数组的的一部分,并返回一个新数组
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="demo">点击按钮截取数组下标 1 到 2 的元素。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var fruits = ["语文", "数学", "英文", "地理", "历史"];
var citrus = fruits.slice(1,3);
var x=document.getElementById("demo");
x.innerHTML=citrus;
}
</script>
</body>
</html>
2 splice 从数组中添加或删除元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="demo">点击按钮向数组添加元素。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var fruits = ["语文", "数学", "英文", "地理", "历史"];
fruits.splice(2,0,"美术","体育");
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>
</body>
</html>
WEB前端互动交流群 434623999
原文地址:https://www.cnblogs.com/CCDS01/p/8157662.html