js动态添加数组可以按下面的步骤:
1、在数组的开头添加新元素 - unshift()
源代码:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to add elements to the array</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruitsunshift("Lemon","Pineapple");
var x=documentgetElementById("demo");
xinnerHTML=fruits;
}
</script>
<p><b>Note:</b> The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em></p>
</body>
</html>
测试结果:
Lemon,Pineapple,Banana,Orange,Apple,Mango
2、在数组的第2位置添加一个元素 - splice()
源代码:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to add elements to the array</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruitssplice(2,0,"Lemon","Kiwi");
var x=documentgetElementById("demo");
xinnerHTML=fruits;
}
</script>
</body>
</html>
测试结果:
Banana,Orange,Lemon,Kiwi,Apple,Mango
3、数组的末尾添加新的元素 - push()
源代码:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to add a new element to the array</p>
<button onclick="myFunction()">Try it</button>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction()
{
fruitspush("Kiwi")
var x=documentgetElementById("demo");
xinnerHTML=fruits;
}
</script>
</body>
</html>
测试结果:
Banana,Orange,Apple,Mango,Kiwi
用js动态生成tr和td
<script>
functiononchecks(){
vartr1=documentgetelementbyid("tb")insertrow();
vartd1=tr1insertcell();
td1width="100px";
td1align="center";
td1innerhtml="第一页";
vartd2=tr1insertcell();
td2width="100px";
td2innerhtml="第二页";
}
</script>
js中添加数组用push示例如下:
1、创建一个数组并赋值,创建数组指定长度,但实际上所有情况下数组都是变长的,仍然可以将元素存储在规定长度以外的,但时长度会随之改变。
2、数组的元素的访问,获取数组的元素值,给数组元素赋予新的值。
3、数组元素的添加,将一个或多个新元素添加到数组结尾,并返回数组新长度。
4、删除从指定位置开始的指定数量元素,数组形式返回所移除的元素。
欢迎分享,转载请注明来源:浪漫分享网
评论列表(0条)