批改状态:未批改
老师批语:
1.用foreach遍历数组,在console中显示;利用splice增加和删除数组中的元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>forEach遍历数组</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
//总结:forEach的原理就是:1、把数组或者对象转换成数组里面的键值赋值给一个----函数(value,key,array),
// 然后用--数组.forEach()方法遍历数组中的元素。
var user = [
'html',
'css',
520,
[13,17,19],
function(x,y) {
return x+y;
}
];
user.forEach(function(value,index,array){
// 参数说明 当前的值,当前的健,全部数组成员等同于user
console.log(array[index]);
});
console.log(user[0]);
console.log(user[1]);
console.log(user[2]);
console.log(user[3]);
console.log(user[3][1]);
console.log(user[4](7,9));
var lis = document.getElementsByTagName('li')
// 用for 遍历 lis内的数组成员 此时lis是个对象 不能用forEach
for (var i =0;i<lis.length;i++) {
if (i%2!==0){
lis[i].style.backgroundColor='blue';
}
}
// 可以用 splice()命令 来取出类数组的对象 取出以后就会变成数组类型
// splice()命令有2个参数 第一个是起始索引 第二个是结束索引 结束索引位置的值将会丢弃
var user =Array.prototype.slice.call(lis);
// 取出以后就可以用数组的方式 来遍历成员
user.forEach(function(value,index,array){
if (index%2===0){
lis[index].style.backgroundColor='red';
}
});
// splice()命令的用法说明 该命令返回被操作后的数组 原数组将会被修改
// 第一个参数(需要操作的起始索引 -1代表最后一个位置)
// 第二个参数 1代表删除(如果第三个参数有值就是替换) 0代表不删除(如果第三个参数有值就是添加)
// 第三个参数是需要添加或者修改的值(取决于第二个参数) 后面可以有N个第三参数
var wyc = [1,2,3,4,5,6,7,8,9];
wyc.splice(1,0,'张飞燕');//在索引1的位置添加 张飞燕
// console.log(wyc);
var zfy = [1,2,3,4,5,6,7,8,9];
zfy.splice(2,5,'陈含静');//在索引2的位置替换 陈含静
// console.log(zfy);
var xw = [1,2,3,4,5,6,7,8,9];
xw.splice(3,2);//删除索引3的位置的数组成员
// console.log(xw);
var hs = [1,2,3,4,5,6,7,8,9];
hs.splice(-1,1,'PHP');//在最后一个索引位置替换 'PHP'
// console.log(hs;
var chj = [1,2,3,4,5,6,7,8,9];
chj.splice(chj.length,1,'html')//在最后一个索引位置增加 'html'
// console.log(chj);
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号