for...of循環
這個直接看代碼吧
1.遍歷數組
var arr = [1,2,3,4,5];
for(let val of arr.values()){
console.log(val)
}
//1
//2
//3
//4
//5
2.遍歷索引
var arr = [1,2,3,4,5];
for(let index of arr.keys()){
console.log(index)
}
//0
//1
//2
//3
//4
3.遍歷值和索引
var arr = [1,2,3,4,5];
for(let item of arr.entries()){
console.log(item)
}
//第一個是索引,第二個是值
// [0, 1]
// [1, 2]
// [2, 3]
// [3, 4]
// [4, 5]
4.上面的結果看起來和平時看的不一樣,看下面
var arr = [1,2,3,4,5];
for(let [key,val] of arr.entries()){
console.log(key,val)
}
// 0 1
// 1 2
// 2 3
// 3 4
// 4 5
在for...of中
數組多了三個屬性
arr.values() //數組的值
arr.keys() //數組的下標
arr.entries() //數組的某一項
for...of 和for...in 的區別
for...in
語句以任意順序迭代對象的可枚舉屬性(可以枚舉屬性)
for...of
語句迭代可迭代對象定義爲迭代的數據(只枚舉數據)
var arr = [1,2,3,4,5];
//設置數組,並給數組的原型上添加屬性
Array.prototype.name = "Name";
//for...of方法打印
for(let val of arr){
console.log(val)
}
// 1,2,3,4,5
//for...in方法打印
//1,2,3,4,5,name
for(let item in arr){
console.log(arr[item])
}
for...of 的實用案例
arguments是個類數組對象,通常先要將其轉換爲數組才能遍歷,但for...of可以直接遍歷
function sum() {
let sum = 0
for (let num of arguments) {
sum += num
}
console.log(sum); //15
}
sum(1, 2, 3, 4, 5)
遍歷字符串
let name = 'Asher';
for (let char of name) {
console.log(char); //A s h e r
}