Javascript & Discord.js - 重复一个数组的长度

Javascript & Discord.js - Repeating something the length of an array

我想知道如何根据数组中的内容重复次数。

这是我试过的方法,但没有用:

var channels = [ '407711330943107072' ]

for (let i in channels.length) {
   console.log(channels[i - 1])
       var channel = client.channels.get(channels[i - 1])
       channel.setTopic(description)
      }

有谁知道为什么这不起作用,或者有更好的方法吗?

谢谢!

使用for..of

for (const channelId of channels) {
   console.log(channelId);
   const channel = client.channels.get(channelId);
   channel.setTopic(description);
}

我猜你的没有工作,因为你试图迭代 channels.length,这是一个数字,不可迭代。

Iterable protocol

let channels = ['example_value', 'second_value']

for (let i in channels) {
   console.log(channels[i])
   //do stuff
}

你在循环时犯了一个小错误。执行 for let i in array 将遍历每个元素。您还希望使用 i 而不是 i-1

直接访问这些值