1、Map
map() 方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。不会改变原数组。
const arr = ['red', 'blue', 'green']
const newArr = arr.map(function (ele, index) {
// console.log(ele) //数组元素
// console.log(index) //索引号
return ele + '颜色'
})
console.log(newArr) //输出新数组
console.log(newArr.join()) //逗号分隔
console.log(newArr.join('')) //小括号是空字符串,元素之间没有分隔符
console.log(newArr.join('|')) //用 | 分隔
注意:
- map的回调函数中支持return返回值,return的是什么,相当于把数组中的这一项变为什么(并不影响原来的数组,只是把原数组克隆了一份,把克隆这一份的数组中对应项改变)
- map的执行速度更快,比forEach的执行速度快了70%;
- 能用forEach()做到的,map()同样可以。
- map()会分配内存空间存储新数组并返回,forEach()不会返回数组
使用场景:
map适用于你要改变数据值的时候,不仅在于它更快,而且返回一个新的数组,这样可以提高复用性(map(),filter(),reduce())等组合使用。
var arr = [1, 2, 3, 4, 5]
var newArr = arr.map(num => num * 3).filter(num => num > 9)
// newArr = [12, 15]
2、forEach (Es6)
forEach() 方法对数组的每个元素执行一次给定的函数。
注意:
- forEach()会改变原数组的方法
- forEach() 方法对数组的每个元素执行一次提供的函数。总是返回undefined
- 数组中有几项,那么传递进去的匿名回调函数就需要执行几次
- forEach和map用法类似,都可以遍历到数组的每个元素,而且参数一致;
- forEach 只能操作数组 (item,index) 系统固定第一个是值item,第二个是index下标 不可以改变顺序
使用场景:当我们对数组的元素进行处理时(例如:增加元素,元素值改变),可以使用这个函数。
forEach()常用于遍历数组,用于调用数组的每一个元素,并将其传递给回调函数。传输函数不需要返回值。实例:
var arr = [8, 3, 6, 77, 5]
try {
arr.forEach((item, index) => {
if (item < 5) {
throw new Error("err")//创建一个新的error
}
//只打印8 说明跳出了循环
console.log(item)
})
} catch (e) {
console.log(e.err)
//扔掉
if (e.err !== "err") {
throw e
}
}
Map forEach对比 实例:
var arr = [1,2,3,4,5]
var l1 = arr.forEach(function(value,index){
//遍历到所有数组元素
console.log(value)
return value + 10
});
console.log(l1) //undefined 只返回undefined
var l2 = arr.map(function(value,index){
//遍历到所有数组元素
console.log(value)
return value + 5
});
console.log(l2) //[6, 7, 8, 9, 10] 返回一个新数组
3、For in 循环
for in
语句循环遍历对象的属性,实例:
let obj = {
uname: 'linsir',
age: 19,
gender: '女'
}
for (let k in obj) {
console.log(k) // 属性名 (字符串) 'uname' 'age'
console.log(obj.k) //undefined
console.log(obj[k]) //输出属性值
}
- for in 循环遍历 person 对象
- 每次迭代返回一个键 (x)
- 键用于访问键的值
- 键的值为 person[x]
for in
语句也可以遍历数组的属性(不推荐使用),实例:
let arr = ['linsir', 'lxx', 'wyb']
for (let k in arr) {
console.log(k) //数组的下标(索引号) 但是是字符串 '0'
console.log(arr[k]) //输出属性值
}
注意:
如果索引顺序很重要,请不要在数组上使用 for in。
索引顺序依赖于实现,可能不会按照您期望的顺序访问数组值。
当顺序很重要时,最好使用 for 循环、for of 循环或 Array.forEach()。
案例:遍历数组对象
需求:把准备好的数据渲染对应到列表中
<style>
table {
width: 600px;
text-align: center;
}
table,
th,
td {
border: 1px solid #ccc;
border-collapse: collapse;
}
caption {
font-size: 18px;
margin-bottom: 10px;
font-weight: 700;
}
tr {
height: 40px;
cursor: pointer;
}
table tr:nth-child(1) {
background-color: #ddd;
}
table tr:not(:first-child):hover {
background-color: #eee;
}
</style>
</head>
<body>
<h2>学生信息</h2>
<table>
<caption>学生列表</caption>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>家乡</th>
</tr>
<script>
// 1. 数据准备
let students = [
{ name: 'linsir', age: 18, gender: '女', hometown: '江西省' },
{ name: 'lxx', age: 23, gender: '女', hometown: '江西省' },
{ name: 'wyb', age: 24, gender: '男', hometown: '河南省' },
{ name: 'hyj', age: 18, gender: '男', hometown: '广东省' },
{ name: 'hl', age: 16, gender: '女', hometown: '广东省' }
]
// 2. 渲染页面
for (let i = 0; i < students.length; i++) {
document.write(`
<tr>
<td>${i + 1}</td>
<td>${students[i].name}</td>
<td>${students[i].age}</td>
<td>${students[i].gender}</td>
<td>${students[i].hometown}</td>
</tr>
`)
}
</script>
</table>
</body>
4、For Of 循环(Es6)
for of
语句循环遍历可迭代对象的值。(不能遍历对象)
ES6新增了 遍历器(Iterator)机制,为不同的数据结构提供统一的访问机制。只要部署了Iterator的数据结构都可以使用 for of 完成遍历操作,每次迭代分配的是 属性值
补充 : 因为迭代的顺序是依赖于执行环境的,所以数组遍历不一定按次序访问元素。 当迭代访问次序重要的 arrays 时用整数索引去进行 for 循环 (或使用 Array.prototype.forEach() 或 for...of 循环)
它允许你循环遍历可迭代的数据结构,例如数组、字符串、映射、节点列表等:
//语法:
for (variable of iterable) {
// code block to be executed
}
variable - 对于每次迭代,下一个属性的值都会分配给变量。变量可以用 const、let 或 var 声明。
iterable - 具有可迭代属性的对象。
遍历数组,实例:
const cars = ["BMW", "Volvo", "Mini"]
let text = ""
for (let x of cars) {
text += x
}
遍历字符串,实例:
let language = "JavaScript"
let text = ""
for (let x of language) {
text += x
}
注意:
for in总是得到对象的key或数组,字符串的下标,而for of和forEach一样,是直接得到值结果
for...in循环遍历一个object所有的可枚举属性,for...of遍历具有iterator接口的数据结构
for in
遍历(当前对象及其原型上的)每一个属性名称,
for of遍历(当前对象上的)每一个属性值
实例:
Array.prototype.arrCustom = function () {}
Object.prototype.objCustom = function () {}
let iterable = [20,30,40]
iterable.li = "hello"
for (let i in iterable) {
console.log(i) // 0, 1, 2, "li", "arrCustom", "objCustom"
}
for (let i of iterable) {
console.log(i) // 20,30,40
}