2016-02-24 2 views
2

Я изучаю код Javascript. Я пытаюсь создать генератор случайных котировок. Идея заключается в том, что у меня есть метод, который создает многомерный массив, причем каждый массив элементов имеет цитату и имя автора. Этот метод возвращает многомерный массив.Неожиданная ошибка типа - Javascript, многомерные массивы

Я присваиваю этот возвращаемый многомерный массив переменной и выбираю случайный массив элементов. Это дает мне «Неожиданную ошибку типа» в консоли.

<script> 
    var colors = ['#16a085', '#27ae60', '#2c3e50', '#f39c12', '#e74c3c', '#9b59b6', 
        '#FB6964', '#342224', '#472E32', '#BDBB99', '#77B1A9', '#73A857']; 

    console.log("Hi!"); 

    function getQuote(){ 
     var quotesAndAuthors = 
     [ 
     ['But suicides have a special language. Like carpenters, they want to know "which tools", they never ask "why build"', "Anne Sexton"], 
     ['Here is the world. Beautiful and terrible things will happen. Dont be afraid', 'Frederick Buechner'], 
     ['All grown-ups were once children, but only a few of them remember it', 'Alexander de Saint-Exupery'], 
     ['It was love at first sight, at last sight, at ever ever sight', 'Vladimir Nabokov'], 
     ['A paradise the color of hell flames, but a paradise nonetheless', 'Vladimir Nabokov'], 
     ['There is nothing like the deep breaths after laughing that hard. Nothing in the world like a sore stomach for the right reasons','Stephen Chbosky'], 
     ['And then suddenly, something is over','Louise Gluck'], 
     ['Adventure is out there!', 'Up (Pixar)'], 
     ['The strong do what they can, and the weak suffer what the must', 'Thucydides'], 
     ['But who prays for Satan? Who, in eighteen centuries, has had the common humanity to pray for the one sinner that needed it most?', 'Mark Twain'], 
     ['I stopped explaining myself when I realized people only understand from their level of perception', 'Unknown'], 
     ['Unexpressed emotions will never die. They are buried alive and will come forth in uglier ways', 'Sigmund Freud'], 
     ['Genius might be the ability to say a profound thing in a simple way', 'Charles Bukowski'] 
     ]; 
     return quotesAndAuthors; 
    } 

    function generate(){ 
     var pickColor = Math.floor(Math.random * colors.length); 

     $('html body').animate({ 
     backgroundColor: colors[pickColor] 
     }, 1000); 

     $('#text #author').animate({ 
     color: colors[pickColor] 
     }, 500); 

     $('.buttons').animate({ 
     backgroundColor: colors[pickColor] 
     },500); 



     var quotes = getQuote(); 
     var n = Math.floor(Math.random * quotes.length); 
     var quoteText = quotes[n][0]; 
     var quoteAuthor = quotes[n][1]; 

     $('#text').text(quoteText); 
     $('#author').text(quoteAuthor); 
    } 

    $(document).ready(function(){ 
     generate(); 
     alert("Testing"); 
     $('#quoteButton').on('click', generate()); 
    }); 

</script> 

Также будут оценены предложения по эффективному использованию котировок.

ответ

1

random - это функция, а не свойство. Вы должны использовать paranthesis как

var n = Math.floor(Math.random() * quotes.length); 

Кроме того, при добавлении обработчиков событий, вы не должны использовать paranthesis, так как это будет вызывать метод еще до того, щелкните событие. Просто укажите имя функции.

$('#quoteButton').on('click', generate); 

Также лучше использовать arrary объектов в вашем случае, как показано ниже:

var quotesAndAuthors = [ 
     { 
     "quote" : "But suicides have a special language", 
     "athour" : "Anne Sexton" 
     }, 
     { 
     "quote" : "All grown-ups were once children", 
     "athour" : "Alexander de Saint-Exupery" 
     } 

     ]; 

И вы можете получить доступ к котировке, как показано ниже, используя либо методу:

console.log(quotesAndAuthors[0]["quote"]); 
console.log(quotesAndAuthors[0].quote); 
+1

* "random - это функция, а не свойство." * - Разве это не свойство, которое ссылается на функцию? Не все ли объектные методы в основном являются объектами, которые относятся к функциям? – nnnnnn

1

Вы хотели позвонить Math.random(), потому что это функция (обратите внимание на скобки). Это вызвало вашу ошибку.

Смежные вопросы