js如何动态添加数组?

JavaScript09

js如何动态添加数组?,第1张

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

有三种方法可以实现,分别如下:

第一种、直接document.write:

<script language="javascript">

document.write("<script src='test.js'><\/script>")

</script>

第二种、动态改变已有script的src属性

<script src='' id="s1"></script>

<script language="javascript">

s1.src="test.js"

</script>

第三种、动态创建script元素:

<script>

var oHead = document.getElementsByTagName('HEAD').item(0)

var oScript= document.createElement("script")

oScript.type = "text/javascript"

oScript.src="test.js"

oHead.appendChild( oScript)

</script>

注意:第三种方法使用时,请注意路径。

你好,

原生JS添加一个JS文件其实比较简单:

// 首先创建一个script标签

var script = document.createElement('script')

// 接着就可以给这个标签指定要加载的文件地址

script.src = './abc/123/cde.js'

// 如果后面的逻辑需要依赖这个js文件,那么需要在该JS完成加载后再执行其他逻辑

script.onload = function() {

    // script已经加载完毕,继续其他逻辑

    // 假如加载的jquery库,则接下来可以这么写

    $('body').css('backgroundColor', 'red')

}

// 当然,要真正执行加载文件,还需要将script标签添加到页面中

document.head.appendChild(script)

好了,就是这么简单。当然还有很多细节,比如考虑到页面代码整洁,加载后删除该标签也是可以的,而且很多库的loader方法也是有这方面功能处理的。

希望能解决你的问题。