JavaScript数组前面插入元素的方法
更新时间:2015年04月06日 12:30:28 作者:work24
这篇文章主要介绍了JavaScript数组前面插入元素的方法,涉及javascript中unshift方法的使用技巧,非常具有实用价值,需要的朋友可以参考下
本文实例讲述了JavaScript数组前面插入元素的方法。分享给大家供大家参考。具体如下:
JS数组带有一个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>
<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
unshift在ie8及之前的版本工作有些问题,数组会插入元素,但是返回值是undefined
希望本文所述对大家的javascript程序设计有所帮助。
相关文章
JavaScript中break、continue和return的用法区别实例分析
这篇文章主要介绍了JavaScript中break、continue和return的用法区别,结合实例形式详细对比分析了JavaScript中break、continue和return的基本功能、使用方法、区别与操作注意事项,需要的朋友可以参考下2020-03-03微信小程序页面跳转功能之从列表的item项跳转到下一个页面的方法
这篇文章主要介绍了微信小程序页面跳转功能之从列表的item项跳转到下一个页面的方法,结合具体实例形式总结分析了微信小程序页面跳转及列表item项跳转页面的相关操作技巧,需要的朋友可以参考下2017-11-11javascript function调用时的参数检测常用办法
js中并不直接支持类似c#的方法重载,所以只能变相的来解决,示意代码:(利用了内置属性arguments)2010-02-02
最新评论