
在JavaScript中,常用Array来存储和 *** 作对象:
Array:
新建:var ary = new Array()或 var ary = []
增加:ary.push(value)
删除:delete ary[n]
遍历:for ( var i=0 i <ary.length ++i ) ary[i]
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
声明创建一个数组对象: var arr = new Array() 或者 var arr = []
连接两个或者多个数组,并且返回该数组,语法: array.concat(object,object,......)
通过指定字符(参数)对数据进行分割,返回字符串,参数省略的话则用默认用逗号为分隔符
删除数组的最后一个对象,返回该删除元素的值
向数组末尾添加一个或者多个对象,语法: array.push(newObject1,newObject2,.....)
删除数组的第一个对象,并返回删除的元素
向数组开头添加一个或者多个元素,并返回新的长度
从已知数组中返回指定选中的数据(不包括end 对应的元素),如果省略 end 将复制 start 之后的所有元素,该 *** 作不会修改原数组的数据, slice(start,end)
向数组中删除/添加对象,并返回被删除的元素
splice(index,count,item1,item2,......)
方法用户对数组的排序, sort(sortby) ,sortby可选,必须是函数。如调用方法没有使用参数,则按字母顺序进行排序。
只要有一个满足的就返回true,没有满足的返回false
验证数组中是否每个元素都满足指定的条件
没有返回值,可以不知道数组长度
arr.forEach(function(res,index){ })
返回值组成新数组,原数组不变
过滤通过条件的元素组成一个新数组,原数组不变
查找出第一个符合条件的数组成员,并返回该成员,如果没有找到就返回undefine
找到的是位置,找不到返回 -1
填充, arr.fill(填充的东西,start,end) 包括end
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)