数组长度超过了javascript所需的数量

时间:2017-11-18 10:17:08

标签: javascript

我在Javascript中有一个这样的数组:

for (int i = 0; i < playerTwoGuesses.Length; i++)
        {
            Thread.Sleep(1400);
            Console.Write("Guess: ");
            count = 0;

            do
            {
                try
                {
                    playerTwoGuesses[i] = char.Parse(Console.ReadLine());
                    validGuess = true;
                }
                catch (Exception)
                {
                    Console.WriteLine("Please enter a single character only.");
                }
            } while (validGuess == false);


            for (int j = 0; j < playerOneDisguised.Length; j++)
            {
                if (playerOneCharacters[j] == playerTwoGuesses[i])
                {
                    playerOneDisguised[j] = playerTwoGuesses[i];

                }
                else
                {
                    lives = lives - 1;

                }
            }


            if (lives == 0)
            {
                Console.WriteLine("Oh no! It seems you've lost. Closing game in 5 seconds.");
                Thread.Sleep(5000);
                Environment.Exit(0);
            }


            Console.WriteLine(playerOneDisguised);


            for (int k = 0; k < playerOneDisguised.Length; k++)
            {
                if (playerOneDisguised[k] != '*')
                {
                    count = count + 1;
                    if (count == playerOneDisguised.Length)
                    {
                        Console.WriteLine("Congratulations you've won!");
                        Thread.Sleep(1000);
                        Console.WriteLine("Closing game in 5 seconds.");
                        Thread.Sleep(5000);
                        Environment.Exit(0);
                    }
                }
            }
        }

218被警告而不是3.我只需要一个包含3个项而不是218的数组。

我该如何解决?

4 个答案:

答案 0 :(得分:1)

books[3]将在第四位添加元素&amp; 0-3位将为空,同样books[218]将位于第219位。

因此长度为219

答案 1 :(得分:1)

您可以使用Array#filterBoolean过滤稀疏元素作为回调。

这适用于truthy个项目。

var books = [];
books[3] = 'abcds';
books[54] = 'point';
books[218] = 'qwerty';

var allBooks = books.filter(Boolean);

console.log(allBooks.length);
console.log(allBooks);

对于falsy值,您需要通过使用Array#forEach进行迭代并推送所有项目来采用不同的方法。

forEach仅访问非稀疏项目。

var books = [];
books[3] = 'abcds';
books[54] = 'point';
books[42] = undefined;
books[55] = 0;
books[218] = 'qwerty';

var allBooks = [];

books.forEach(a => allBooks.push(a));

console.log(allBooks.length);
console.log(allBooks);

答案 2 :(得分:1)

而不是在所提到的索引处存储值。您可以在数组中以对象的形式存储值。

var books = [];
books.push({3:'abcds'});
books.push({54: 'point'});
books.push({218: 'qwerty'});
console.log(books.length);

答案 3 :(得分:-1)

获取数组内值的方法是Object.values(books).length