最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

为什么join(“,”)无法与我的数组一起使用?

IT培训 admin 20浏览 0评论

为什么join(“,”)无法与我的数组一起使用?

我正在尝试为某事制造一个不和谐的机器人,但我不知道为什么会这样。回想起来,这并不是一个大问题,但是了解推理是一个好主意

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

// 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(“,”)将所有内容隔开。所以我不知道有什么区别。

回答如下:

此行可能是罪魁祸首:

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(', '),则[ 'a', 'b', 'c' ]元素将转换为字符串:

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

请注意缺少空格!

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

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

要解决此问题,请尝试以下更改:

obtainedCards = obtainedCards.concat(cards);

为什么join(“,”)无法与我的数组一起使用?

我正在尝试为某事制造一个不和谐的机器人,但我不知道为什么会这样。回想起来,这并不是一个大问题,但是了解推理是一个好主意

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

// 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(“,”)将所有内容隔开。所以我不知道有什么区别。

回答如下:

此行可能是罪魁祸首:

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(', '),则[ 'a', 'b', 'c' ]元素将转换为字符串:

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

请注意缺少空格!

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

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

要解决此问题,请尝试以下更改:

obtainedCards = obtainedCards.concat(cards);
11136
发布评论

评论列表 (0)

  1. 暂无评论