场景
有时候在拿到接口反回数据的时候我们需要循环数据,就可以用for of / in
当然还有好多其他的循环,这里忽略
首先 先看一个循环的 数组
注意区分 of in 返回结果
data() {
return {
list: [
{
name: "帅帅1",
age: 11
},
{
name: "帅帅2",
age: 12,
some: 1
},
{
name: "帅帅3",
age: 13
},
{
name: "帅帅4",
age: 14
},
{
name: "帅帅5",
age: 15
},
{
name: "帅帅6",
age: 16
}
]
};
},
created() {
for (const s of this.list) { // 可以拿到每一项
console.log(s.name); // 帅帅1 帅帅2 帅帅3 帅帅4 帅帅5 帅帅6
}
for (const s in this.list) { // 只能拿到索引
console.log(s); // 0 1 2 3 4 5
}
for (const s in this.list) {
console.log(s.name); // undefined undefined undefined undefined undefined undefined
}
},
let 和 const 有什么区别
因为每一次的迭代都会声明一个全新的key, 所有的赋值都是给一个新的变量赋值,而没有改变原来的值。那使用let 和 const 有什么区别吗? 当然有了,还是在于const 声明的变量不能重新赋值了,所以如果for-in 或for- of 中使用const 声明了变量( 如key), 循环体中,就不能给key 赋新值了,如果使用let ,那就无所谓了,想干什么就干什么,只不过for-in 或for-of 中,我们很少改变key 值,所以他们在实际使用时就没有什么区别了
这里再看一下 es6中的块作用域
正常定义俩个 同样的 常量是会报错的
const a=10;
const a=10;// 报错 a 已经定义了
利用块级作用域就可以解决
{
const a=10;
}
{
const a=10;
}
// 还有一点就是 使用 const 和let 定义的数据 并不会在 顶层对象window上
const a=10;
console.log(window.a); // undefined
还有一个小知识就是 数组也可以使用 indexOf(element) 方法
如果数组中有这个元素的话 返回数组中 所在的下标位置
没有返回 -1
并且对大小写 敏感哈 区分大小写的
var arr=["hello","world","VUE","vue","angular","react"];
console.log(arr.indexOf("VUE")); // 输出 2