【问题标题】:Why does join(", ") not work with my array?为什么 join(", ") 不适用于我的数组?
【发布时间】:2020-08-31 15:20:33
【问题描述】:

我正在尝试为某事制作一个不和谐的机器人,但我无法弄清楚为什么会发生这种情况。回想起来,这并不是什么大问题,但知道其中的原因是个好主意

基本上,我有一个看起来像这样的数组:

// Boosters.js
exports.test = ["Card", "Card2", "Card3", "Card4", "Card5", 
                "Card6", "Card7", "Card8", "Card9", "Card10"];

然后,在另一个文件中,我有一个函数:

// Functions.js
var pack = [];

let getCards = function getCards()
{
    var obtainedCards = [];

    for(i = 0; i < 7; i++)
    {
        var cards = Boosters.test[Math.floor(Math.random() * Boosters.test.length)];
        obtainedCards.push(cards);
    }

   // Adds the cards from the obtained cards variable to the pack
   pack.push(obtainedCards);

}

然后在第三个文件中,我有一个命令会像这样调用函数:

// 
case "pack":
    Functions.getCards();
    message.channel.send("Cards obtained: " + Functions.pack.join(", "));

这里没有问题,它有效。问题是,在 Discord 中它看起来像:

获得的卡片:Card1,Card5,Card2,Card6,Card2,Card1,Card7

基本上,它忽略了 join() 函数。奇怪的是,如果我打印原始 test[],机器人实际上使用 join(", ") 将所有内容隔开。所以我不知道有什么区别。

【问题讨论】:

  • Discord 输出有什么问题?
  • 他使用了.join(", "),但输出中没有空格
  • obtainedCards 是一个数组。 pack 是一个数组。将一个数组推送到一个数组应该是一个嵌套数组。所以pack.join 似乎是太高了。
  • 我认为您正在实现从数组到字符串的自动转换,其作用类似于join()。提示:'myarray:' + [ 'a', 'b' ]
  • 我认为您的问题是您需要使用concat() 而不是push() 来将数组添加到pack 数组中。或者可能拼接

标签: javascript arrays node.js discord.js


【解决方案1】:

这条线很可能是罪魁祸首:

obtainedCards.push(cards);

要了解原因,请考虑以下代码:

let xs = [ 'x', 'y', 'z' ];

xs.push([ 'a', 'b', 'c' ]);

// xs is now: 
// [ 'x', 'y', 'z', [ 'a', 'b', 'c' ] ] 
//
// ... but you might have expected this: 
// [ 'x', 'y', 'z', 'a', 'b', 'c' ]

如果我们join(', ')this,则[ 'a', 'b', 'c' ]元素被转换为字符串:

xs.join(', ') // "x, y, z, a,b,c"

注意没有空格!

只要数组自动转换为字符串,就会发生这种行为:

'xyz' + [ 'a', 'b', 'c' ] // "xyza,b,c"

要修复它,请尝试以下更改:

obtainedCards = obtainedCards.concat(cards);

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多