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



我已经做了我认为会产生类别的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不是函数";

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()实际上返回数组的长度,而不是数组本身。

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);

最新更新