我正在学习编写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>
此外,有关如何更有效地存储报价的建议将不胜感激。
答案 0 :(得分:1)
您想要致电Math.random()
因为这是一个功能(请注意括号)。这就产生了你的错误。
答案 1 :(得分:1)
random是一个函数,而不是一个属性。你应该使用像
这样的paranthesisvar 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);
答案 2 :(得分:1)
.random不是Math对象的属性。 Math.random()是一种方法。