簡體   English   中英

將返回值從一個數組傳遞到另一個數組

[英]Passing a return value from one array to another array

當用戶單擊按鈕時,下面的代碼顯示來自數組的單個單詞。 我希望顯示以前的單詞,所以我要推送到一個新數組。 我想做的是將my_array.randsplice()的返回值傳遞給第二個數組,這樣我就可以在同一索引位置顯示第二個數組的內容。 我正在嘗試(未成功)執行的操作是顯示一個數組中的單詞以及第二個數組中單詞的定義,但我無法弄清楚。 我是否需要兩個數組來執行此操作,或者可以拼接包含兩個數據集的多維數組? 任何幫助表示贊賞。

    <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Word List</title>
<style>
.wordList {
    text-decoration: none;
    color: green;
}
</style>
<script>
Array.prototype.randsplice = function(){
    var ri = Math.floor(Math.random() * this.length);
    var rs = this.splice(ri, 1);
    return rs;  
}
var new_array =[];
var my_array = [' Apple',
        ' Bat',
        ' Car',
        ' Dog',
        ' Elephant',
        ];


function getWord() {
    var result = my_array.randsplice();
    new_array.push(result);
    document.getElementById('word_list').innerHTML = new_array;
}

</script>
</head>
<body>
<div id="main">

          <div class="header">
            <h1 id="game_title">Title Here</h1> 
            <hr>
            <button onclick="getWord()">Get Word</button>
            <h2 id="word_list_title">Word List:</h2>
            <h2 id="word_list" class="wordList"> </h2>
          </div>
</div>

</body>
</html>

我認為您正在尋找的是一組對象。

var dictionary = [ {word: "Apple", meaning: "A red fruit"}, {word: "Bat", meaning: "A nocturnal bird"} ];

然后,您可以像這樣訪問單詞:

dictionary[0].word    // "Apple"

意思是這樣的:

dictionary[0].meaning    // "A red fruit"

要從字典中獲取“隨機”字,您需要做的就是用隨機索引替換“ 0”。 希望這很清楚!

var ri = Math.floor(Math.random()*dictionary.length);

dictionary[ri].word // Gives a random word

dictionary[ri].meaning // Gives that random words meaning

function getWord() {
var ri = Math.floor(Math.random()*dictionary.length);
document.getElementById('word_list').innerHTML = dictionary[ri].word + ":" + dictionary[ri].meaning;
dictionary.splice(ri, 1);
}

這個答案的特征是一個以單詞為鍵和含義的對象。 此外,如果數組為空,則Array.prototype.randomSplice返回undefined,供以后在答案中使用。

 Array.prototype.randomSplice = function () { return this.length && this.splice(Math.random() * this.length | 0, 1) || undefined; } var wordList = [], data = { Apple: 'An apple a day', Bat: 'Out of hell', Car: 'So dirty', Dog: 'The best friend', Elephant: 'Remember the life' }, words = Object.keys(data); function getWord() { var word = words.randomSplice(); if (word) { wordList.push(word); document.getElementById('word').innerHTML = word; document.getElementById('wordMeaning').innerHTML = data[word]; document.getElementById('wordList').innerHTML = wordList.join(', '); } } 
 <button onclick="getWord();">Get Word</button> <h3>Word</h3> <div id="word"></div> <h3>Meaning</h3> <div id="wordMeaning"></div> <h3>List</h3> <div id="wordList"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM