lbi*_*eau 1 javascript loops destructuring variable-assignment ecmascript-6
我正在尝试使用 ES6 语法解构一个对象,然后在循环内重新分配变量。
ES5
this.playlist.forEach((item, i) => {
item.timeoutId = setTimeout(() => {
item.sound.play()
}, 1000 * i)
})
Run Code Online (Sandbox Code Playgroud)
ES6(不工作)
this.playlist.forEach(({sound, timeoutId}, i) => {
timeoutId = setTimeout(() => {
sound.play()
}, 1000 * i)
})
Run Code Online (Sandbox Code Playgroud)
知道为什么它不起作用吗?
它应该可以工作,但有一个警告:
timeoutId = setTimeout(() => {
sound.play()
}, 1000 * i)
Run Code Online (Sandbox Code Playgroud)
timeoutId
是里面的值item.timeoutId
,而不是它的别名。当您为 分配一个值时timeoutId
,它不会被分配回item.timeoutId
。
使用item.timeoutId
取消超时,将无法正常工作,因为item.timeoutId
不包含超时标识。
在示例中,您可以看到timeoutId
保持null
:
timeoutId = setTimeout(() => {
sound.play()
}, 1000 * i)
Run Code Online (Sandbox Code Playgroud)
@guest271314 指出的解决方案是直接分配给属性,使用forEach
(数组)的第三个参数和索引:
const arr=[{ id: 1, timeoutId: null }, { id: 2,timeoutId: null }, { id: 3, timeoutId: null }, { id: 4, timeoutId: null }];
arr.forEach(({sound, timeoutId}, i) => {
timeoutId = setTimeout(() => {
//sound.play()
}, 1000 * i)
})
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2043 次 |
最近记录: |