批改状态:未批改
老师批语:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
//总结:forEach的原理就是:1、把数组或者对象转换成数组里面的键值赋值给一个----函数(value,key,array),然后用--数组.forEach()方法遍历数组中的元素。
arr = [125,'html',987,'php','javascript'];
/* 数组.forEach(function(值,键,回调函数)) ,其中 键、值、回调函数
需要哪个用哪个。用这种格式遍历数组。但是forEach不能遍历对象,需要用
var arr=Array.prototype.slice.call(obj),来把对象obj转换成数组,
1、其中obj对象里面的键必须是0,1,2,3等数字,2、并且对象的最后必须要有--length:值(有几个元素就为几)-- 否则将无法换。
*/
// function obj(value, key, array) {
// //下边两重方式结果一样,前者用的是键和值,后边用的回调函数。
// console.log('['+ key + ']'+ '=>' + value );
// console.log('['+ key + ']'+ '=>' + array[key] );
//
// };
//
// arr.forEach(obj);
//简化写法,可以少一个全局变量obj
// arr.forEach(function(value,index, array){
// console.log('['+ index + ']'+ '=>' + value );
// console.log('['+ index + ']'+ '=>' + array[index] );
// } //函数体的后括号
// ); //函数function的后括号
//对象转换成函数,1、键必须全是纯数字,2、必须要有length:4,负责转换失败。
var user={
'0':'a',
'1':'b',
'2':'c',
'3':'58',
length:4 //必不可少
};
var ar = Array.prototype.slice.call(user);
ar.forEach(function (value,key,array) {
console.log('['+ key + ']'+ '=>' + value );
console.log('['+ key + ']'+ '=>' + array[key] );
});
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号