如何在一组类别ID下创建所有通道的数组?

时间:2020-10-13 23:13:50

标签: discord.js

我已经完成了我认为会产生类别ID数组的工作,这是我的代码尝试使用其ID返回其子频道的键。

    var filtered_category_ids = [""];
    var filtered_category_ids = filtered_category_ids.reduce((acc, id) => 
    acc.push(filtered_category_names.findKey((c) => c.name === name)));
    var filtered_channel_ids = [];
    const children = this.children;
    filtered_category_ids.forEach(element => filtered_channel_ids.push((children.keyArray())));
    console.log(filtered_channel_ids);

但是,在运行它时,出现TypeError“ filtered_category_ids.forEach不是函数”

1 个答案:

答案 0 :(得分:0)

Array.prototype.reduce的第二个参数非常重要。这是acc开始时要使用的值。如果没有第二个参数,它将采用数组中第一个元素的值。

console.log([1, 2, 3].reduce((acc, curr) => acc + curr)) // acc starts as `1`
console.log([1, 2, 3].reduce((acc, curr) => acc + curr, 10)) // but what if we wanted it to start at `10`

使用数组,对象等时,基本上需要此参数。

console.log([1, 2, 3].reduce((acc, curr) => acc.push(curr))) // right now, `acc` is `1` (not an array; does not have the .push() method)

console.log([1, 2, 3].reduce((acc, curr) => acc.push(curr), [])); // start with an empty array

但是,还有第二个问题(从上面的代码片段中可以看到)。 Array.prototype.push()实际上返回数组的 length ,而不是数组本身。

console.log(
  [1, 2, 3].reduce((acc, curr) => {
    acc.push(curr); // push element to array
    return acc; // but return the arr itself
  }, [])
);

// second (simplified) method
console.log([1, 2, 3].reduce((acc, curr) => [...acc, curr], []))

您还可以使用Array.from(),在这种情况下会更简单。

console.log(Array.from([1, 2, 3], (num) => num);


您的代码中还有其他一些奇怪的事情,因此,我建议您这样做:

var filtered_category_names = ['']; // I think you might've meant `category_names` instead of `ids`

// you're trying to get IDs from names, so I'm not sure why you're reducing the ID array (before it's established)
// and using id as a parameter name when you use `name` in the actual function
var filtered_category_ids = Array.from(filtered_category_names, (name) => 
 client.channels.cache.findKey((c) => c.name === name)
);

var filtered_channel_ids = [];
filtered_category_ids.forEach((id) =>
 // filtered_channel_ids.push(children.keyArray()) // you're adding the same value to the array multiple times?

 // get the category's children and add their IDs to the array
 filtered.channel.ids.push(client.channels.cache.get(id).children.keyArray())
);
console.log(filtered_channel_ids);