1.8 KiB
1.8 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7b89367417b2b2512b4b | Use Destructuring Assignment to Assign Variables from Arrays | 1 | 301213 | 使用解构赋值从数组中分配变量 |
Description
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2
变量a
以及b
分别被数组的第一、第二个元素赋值。
我们甚至能在数组解构中使用逗号分隔符,来获取任意一个想要的值:
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5
Instructions
a
与b
的值。使a
、b
能分别获得对方的值。
Tests
tests:
- text: 在交换后,<code>a</code>的值应该为6。
testString: assert(a === 6);
- text: 在交换后,<code>b</code>的值应该为8。
testString: assert(b === 8);
- text: 使用数组解构来交换<code>a</code>和<code>b</code>。
testString: assert(/\[\s*(\w)\s*,\s*(\w)\s*\]\s*=\s*\[\s*\2\s*,\s*\1\s*\]/g.test(code));
Challenge Seed
let a = 8, b = 6;
// change code below this line
// change code above this line
console.log(a); // should be 6
console.log(b); // should be 8
Solution
let a = 8, b = 6;
[a, b] = [b, a];