if...in
const obj = {
name:'jerry',
age:14
}
if('name' in obj){
console.log('我在里面')
}else {
console.log('我不在里面')
}
for...in
遍历数组
使用 for in
去遍历数组,得到的 key
就是数组的索引 index
。
const resDate = results?.db_data?.map((item: any) => {
const obj = {};
for (let index in item) {
obj[`field${JSON.parse(index) + 1}`] = item[index]
}
return obj
})
console.log('resDate-->',resDate)
打印结果: 对象数组,想要改变里面对象的key,自定义key的名字。
for...of
//遍历数组
let arr=[12,23,45,{name:'marry'}]
for(let index of arr){
console.log(index)
}
打印结果
12
23
45
{name: 'marry'}
//遍历对象
let obj={name:'tim',age:14}
for(let index of Object.keys(obj)){
console.log(index)
}
打印结果
name
age
总结:
-
推荐在循环对象属性的时候,使用
for...in
,在遍历数组的时候的时候使用for...of
。 -
for...in
循环出的是key,for...of
循环出的是value -
注意,
for...of
是ES6新引入的特性。修复了ES5引入的for...in
的不足 -
for...of
不能循环普通的对象,需要通过和Object.keys()
搭配使用
for of的出现是为了方便迭代器的使用
for...of语句在可迭代对象(包括 Array, Map, Set, String, TypedArray,arguments 对象等等)上创建一个迭代循环,对每个不同属性的属性值,调用一个自定义的有执行语句的迭代挂钩.
也就是说,for of只可以循环可迭代对象的可迭代属性,不可迭代属性在循环中被忽略了。
并且给与了一个对比的例子
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
console.log(i); // logs 3, 5, 7
}
参考文章:javascript总for of和for in的区别? - SegmentFault 思否