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"]
fruits.unshift("Lemon","Pineapple")
var x=document.getElementById("demo")
x.innerHTML=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"]
fruits.splice(2,0,"Lemon","Kiwi")
var x=document.getElementById("demo")
x.innerHTML=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()
{
fruits.push("Kiwi")
var x=document.getElementById("demo")
x.innerHTML=fruits
}
</script>
</body>
</html>
测试结果:
Banana,Orange,Apple,Mango,Kiwi
给出的建议是老老实实用forEach,不仅可以避免大数组的异常问题,并且从性能角度考虑forEach也是最快的。
Array.prototype.extend = function (other_array) {/* you should include a test to check whether other_array really is an array */
other_array.forEach(function(v) {this.push(v)}, this)
}
function insert(arrfirst,arrlast,index){ //将数组arrlast插入数组arrfirst中,index是想要插入的位置if (index < 0){
index = 0
}else if(index > arrfirst.length){
index = arrfirst.length
}
var arr = []
for (var i = 0 i < index i++){
arr.push(arrfirst[i])
}
for (var i = 0 i < arrlast.length i++){
arr.push(arrlast[i])
}
for (var i = index i < arrfirst.length i++){
arr.push(arrfirst[i])
}
return arr
}
var arr1 = ["1","2","3"]
var arr2 = ["a","b","c"]
console.log(insert(arr1,arr2,0))
alert(insert(arr1,arr2,1))
还有一种方法
function insert(arrfirst,arrlast,index){if (index < 0){
index = 0
}else if(index > arrfirst.length){
index = arrfirst.length
}
for (var i = arrlast.length-1 i >= 0 i--){
arrfirst.splice(index,0,arrlast[i])//是在index位置用arrlast[i]替换掉arrfirst数组中的0个元素
}
return arrfirst
}
var arr1 = ["1","2","3"]
var arr2 = ["a","b","c"]
console.log(insert(arr1,arr2,0))
alert(insert(arr1,arr2,1))
希望能帮到你