我對 JavaScript 很陌生,但對 C 和 java 有很好的經驗。無論出于何種原因,我下面的代碼都不會使用未定義以外的值填充陣列。我試圖簡單地用一組亂數字填充一個陣列以進行二十一點游戲
let randomSuite;
let randomNum
let count = 0;
var cards = new Array(56);
window.onload = function main(){
const suites = [
"H",
"D",
"S",
"C"
];
for(let i = 0 ; i < 56 ; i ){
randomNum = (Math.random * 12) 1;
randomSuite = Math.random * 3;
cards.push = randomNum;
console.log(cards[i]);
count ;
}
alert(cards[1]);
}
function hitFunc(){
alert("works " cards[0]);
}
*{
margin: 0;
padding : 0;
font-family: sans-serif;
}
.main{
width: 100%;
height: 100vh;
background-color:black;
}
.img1{
position: relative;
z-index: -1;
margin: 10px auto 20px;
display: block;
width: 75%;
height: 75%;
}
.img2{
position: relative;
z-index: 1;
margin: 10px auto 20px;
display: block;
bottom: 200px;
right: 400px;
width: 7%;
height: 7%;
}
.hitButton {
z-index: 1;
position: relative;
text-align: center;
left: 225px;
bottom: 550px;
}
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
color: aliceblue;
object-position: center;
}
這就是我所擁有的。警報用于顯示功能正在完成。任何幫助表示贊賞請留下解釋。這是我關于堆疊溢位的第一篇文章,如果有任何方法可以提高我的文章質量,請告訴我。
uj5u.com熱心網友回復:
Math.random是一個函式;采用Math.random()- 相同
push,使用cards.push(randomNum) - 您正在定義一個包含 56 個點的陣列,
new array(56)但由于您正在使用push,您需要創建一個空陣列,以便您使用所需的索引。否則,而不是push,只需將其設定在索引上:cards[i] = randomNum - 不需要
count變數,因為回圈迭代器 (i) 具有相同的值
let randomSuite;
let randomNum
var cards = new Array();
window.onload = function main(){
const suites = [
"H",
"D",
"S",
"C"
];
for(let i = 0 ; i < 56 ; i ){
randomNum = (Math.random() * 12) 1;
randomSuite = Math.random() * 3;
cards.push(randomNum);
}
console.log(cards)
}
*{
margin: 0;
padding : 0;
font-family: sans-serif;
}
.main{
width: 100%;
height: 100vh;
background-color:black;
}
.img1{
position: relative;
z-index: -1;
margin: 10px auto 20px;
display: block;
width: 75%;
height: 75%;
}
.img2{
position: relative;
z-index: 1;
margin: 10px auto 20px;
display: block;
bottom: 200px;
right: 400px;
width: 7%;
height: 7%;
}
.hitButton {
z-index: 1;
position: relative;
text-align: center;
left: 225px;
bottom: 550px;
}
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
color: aliceblue;
object-position: center;
}
uj5u.com熱心網友回復:
用括號呼叫函式
Math.random()并且push()是函式而不是變數,因此您需要使用().
push()將追加到陣列
push()將值附加到陣列。您已經用 10 個值初始化了一個陣列。推送新值將增加陣列大小,但不會在前 10 個位置添加值。
const array = new Array(10);
for(let i = 0; i < 10; i ){
array.push(i);
}
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
解決方案
您應該改為使用array[i] = value;在給定位置上設定值。
const array = new Array(10);
for(let i = 0; i < 10; i ){
array[i] = i;
}
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
如果你想有一個更實用的方式來做這件事,這對于 JavaScript 來說很典型,你可以使用map():
const array = [...new Array(10)].map((_, index) => index);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/479011.html
標籤:javascript 不明确的
下一篇:K-Fold交叉驗證的應用和部署
