Blogger Information
Blog 63
fans 1
comment 0
visits 76079
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
forEach()遍历数组、slice()方法、splice()方法
桃儿的博客
Original
1756 people have browsed it

使用forEach()遍历数组


实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用forEach()遍历数组</title>
</head>
<body>
<script>
    var arr1=[1,2,3,'a','b','c'];
    arr1.forEach(function (value,key,array) {
        // console.log(value);
        // console.log(key);
        // console.log(array);
 console.log('['+key+']'+'=>'+value);
    });
</script>

</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例



通过查手册编写slice()方法的案例, 实现数组元素的添加, 删除和更新操作


实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>slice()方法案例</title>
</head>
<body>
<script>
    var arr2=[1,4,5,6,7,2,3,8,9,'a','b','c','d'];
    arr2.slice(0);//全部截取
    arr2.slice(3,9);//从第3个开始截取到第9个,不包含9,
    arr2.slice(-5);//从倒数第5个截取到最后
    arr2.slice(-5,-2);//从倒数第5个截取到倒数第2个,不包含倒数第2个
    arr2.slice(-2,-5)//结果为空,因为slice()中第一个参数大于第二个参数
    
</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


splice()方法:  删除、增加、更新操作,返回结果始终为被删除或替代的元素。

删除操作:splice( )括中第二个元素为要删除的个数  

添加操作:splice( )括中第二个元素为0

更新操作:splice( ) 括号中第二个元素为要更新的元素个数


实例

  var arr=[1,2,3,4,5,6];
    arr.splice(0,1);//从0开始删除一个元素,返回的是被删除的元素。结果为1。
    arr.splice(1,0,'a','b');//从1开始添加a和b,返回的是空(被删除内容为空),原数组已改变
    arr.splice(2,3,'x','y','z');//更新,从2的位置开始更新3个元素,将3,4,5更新为xyz,返回结果为被删除掉的3,4,5

运行实例 »

点击 "运行实例" 按钮查看在线实例



Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post