gpt4 book ai didi

javascript奇怪的控制台日志

转载 作者:行者123 更新时间:2023-11-30 13:48:21 24 4
gpt4 key购买 nike

我有一个 make 函数赋值给你一个排序数组,其中包含从 1 到 45 的 6 个随机数。所有数组值都不应彼此相等。

我想过一个可以在 Java 中运行的解决方案,但我得到的 JavaScript 控制台日志非常困惑。谁能帮帮我?

"use strict";

var numbers = [];
for(var x = 1; x <46;x++){
numbers.push(x);
}


function LottoTipp(){
var result = [];

for(var i = 0; i <6; i++){
var randomNum = Math.round(Math.random()* 45);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum)
}

return console.log(result) + console.log(numbers);

}

LottoTipp();

控制台日志

[ 34, 7, undefined, undefined, undefined, undefined ]

[ 1, 2, 3, 4, 5, 6 ]

最佳答案

There were three problems:

  • If you want to remove one item of an array you have to splice it by the items index and give a deletecount.

    In your case: numbers.splice(randomNum, 1);

  • You have to use Math.floor instead of Math.round, because Math.floor always down to the nearest integerer, while Math.round searches for the nearest integer wich could be higher than numbers.length.

  • After removing one item the length of the array has been changed. So you have to multiply by numbers.lenght instead of 45.

    In your case: var randomNum = Math.floor(Math.random()* numbers.length);

"use strict";

var numbers = [];
for(var x = 1; x < 46; x++){
numbers.push(x);
}


function LottoTipp(){
var result = [];

for(var i = 0; i < 6; i++){
var randomNum = Math.floor(Math.random()* numbers.length);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum, 1);
}

return console.log(result) + console.log(numbers);

}

LottoTipp();

关于javascript奇怪的控制台日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58834947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com