你能解释一下迭代数组时多个参数的数组破坏在for-of循环中是如何工作的吗?
对于一个参数,x,我得到以下(合理的)迭代行为:
for(let [ x ] of ["1", "2", "3"]) {
console.log(`x=${x}`);
}
output:
x=1
x=2
x=3
但我无法想象如何使用两个参数x和y正确迭代.
尝试:
for(let [ x , y ] of ["1", "2", "3"]) {
console.log(`x=${x}`);
console.log(`y=${y}`);
}
output:
x=1
y=undefined
x=2
y=undefined
x=3
y=undefined
和:
for(let [ x , y ] of [["1", "2", "3"]]){
console.log(`x=${x}`);
console.log(`y=${y}`);
}
要么 –
for(let [ x , y ] of [["1", "2", "3", "4"]]){
console.log(`x=${x}`);
console.log(`y=${y}`);
}
which both output:
x=1
y=2
为什么x,y不继续迭代数组,所以它们会得到值3,4?
更新:
从http://es6katas.org/开始尝试’阵列破坏’kata时,我不得不挣扎.
there的最后一次测试是通过:
it('in for-of loop', () => {
for (var [a, b] of [[0, 1, 2]]) {}
assert.deepEqual([a, b], [1, 2]);
});
最佳答案 在这个例子中:
for(let [x, y] of ["1", "2", "3"]) {
console.log(`x=${x}`);
console.log(`y=${y}`);
}
迭代一个包含3个值的字符串数组,但是您尝试将每个值解包为2个变量.所以第一个用值启动,第二个用undefined启动.
在这个例子中:
for(let [x, y] of [["1", "2", "3", "4"]]){
console.log(`x=${x}`);
console.log(`y=${y}`);
}
迭代一个数组数组,但你只有一个内部数组.
所以迭代器只运行一次.
如果你有4个变量,它们将分别得到值“1”,“2”,“3”,“4”.
但是你只给了2个,所以只有它们才会被启动.
你可以尝试这个:
for(let [x, y, z, w] of [["1", "2", "3", "4"]]){
console.log(`x=${x}`);
console.log(`y=${y}`);
console.log(`z=${z}`);
console.log(`w=${w}`);
}
(中间的示例与最后一个示例完全相同,但每个内部数组中的值较少)
另一方面,如果你有:
for(let [x, y] of [["1", "2"], ["3", "4"]]){
console.log(`x=${x}`);
console.log(`y=${y}`);
}
你会得到:
x=1
y=2
x=3
y=4
更新:
通过您提交的测试,您可以:
// 10: destructuring - array
// To do: make all tests pass, leave the assert lines unchanged!
describe('destructuring arrays makes shorter code', () => {
it('extract value from array, e.g. extract 0 into x like so `let [x] = [0];`', () => {
let [firstValue] = [1]; //enclosed in array
assert.strictEqual(firstValue, 1);
});
it('swap two variables, in one operation', () => {
let [x, y] = ['ax', 'why'];
[x, y] = [y, x]; //swapped right side of the assignment
assert.deepEqual([x, y], ['why', 'ax']);
});
it('leading commas', () => {
const all = ['ax', 'why', 'zet'];
const [,,z] = all; //added one extra leading comma
assert.equal(z, 'zet');
});
it('extract from nested arrays', () => {
const user = [['Some', 'One'], 23];
const [[firstName, surname], age] = user; //enclosed as internal array
const expected = 'Some One = 23 years';
assert.equal(`${firstName} ${surname} = ${age} years`, expected);
});
it('chained assignments', () => {
let c, d;
let [a, b] = [c, d] = [1, 2]; //enclosed a,b as array
assert.deepEqual([a, b, c, d], [1, 2, 1, 2]);
});
it('in for-of loop', () => {
for (var [, a, b] of [[0, 1, 2]]) {} //added extra comma
assert.deepEqual([a, b], [1, 2]);
});
});
这不是解决这个问题的唯一方法.