Skip to content

Commit

Permalink
数组解构 && for of 循环
Browse files Browse the repository at this point in the history
  • Loading branch information
dptms committed Oct 23, 2017
1 parent 387e87c commit 782b76b
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
File renamed without changes.
22 changes: 22 additions & 0 deletions 7.destructuring-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 数组解构
### 获取对应位置的元素
```
const numbers = [1, 2, 3, 4];
const [, two,] = numbers; // 获取数组的第二个元素
const [one, ...others] = numbers; // 获取第一个元素以及剩余的数的数组
```
### 默认值
```
const detail = ['Dp', 'dmtms.com'];
const [name, website, category = 'php'] = detail;
```

### 最常见的用法
* 交换变量的值
```
let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a); // 输出:20
```
58 changes: 58 additions & 0 deletions 8.for-of-loop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# for of
```
// for循环 可读性差、繁琐
const fruits = ['apple', 'banana', 'orange', 'mango'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// forEach 不能终止或者跳过
fruits.forEach(fruit => console.log(fruit));
// for in 遍历对象上的可枚举属性 如果
fruits.describe = 'my favourite fruits';
// describe的内容也会遍历出来
for (let index in fruits) {
console.log(fruits[index]);
}
// for of 支持终止打断,fruit直接就是属性值
for(fruit of fruits){
console.log(fruit);
}
```
### 使用实例
> 可以遍历可迭代对象,可迭代对象就是部署了迭代器接口 `iterable`,很多内置的数据结构提供了内置的遍历器接口。比如 `array` 或者 `map`
```
for(let [index,fruit] of fruits.entries()){
console.log(`${fruit} ranks ${index+1} in my favorite fruits`);
}
```
`for of` 支持循环数组,字符串,`map`,set,arguments等数据结构,但是目前不支持对象

```
// 数组
function sum() {
let total = 0;
for (let num of arguments) {
total += num;
}
console.log(total);
}
sum(23, 432, 65, 767, 23);
// 字符串
let name = 'laravel';
for (let char of name) {
console.log(char);
}
// nodelist
const lis = document.querySelectorAll('li');
for (let li of lis) {
li.addEventListener('click', function () {
this.classList.toggle('completed');
});
}
```

0 comments on commit 782b76b

Please sign in to comment.