我的javascript用于随机生成器

my javascript for a random generator

本文关键字:随机 javascript 用于 我的      更新时间:2023-09-26

我正在自由代码阵营中做一个项目,我让代码工作了,几天后它就不再工作了。

代码:

$(document).ready(function() {
var Quotation = new Array() Quotation[0] = "Damn it Jim, I am a Doctor Not a Miricle Worker!";
Quotation[1] = "Live long, and prosper.";
Quotation[2] = "Space… the final frontier.";
Quotation[3] = "Everyone remember where we parked.";
Quotation[4] = "A little suffering is good for the soul.";
Quotation[5] = "Conquest is easy. Control is not.";
Quotation[6] = "Beam me up, Scotty.";
Quotation[7] = "What does God need with a starship?";
Quotation[8] = "Nuclear wessels.";
Quotation[9] = "You will be assimilated.";
function getQuote("Quotation"); {
  return Math.floor(Math.random() * Quotation.length);
}
$('#btn').click(function() {
  $('#quote').text(quotes[getQuote()]);
});

我知道javascript,但真的不知道自己在做什么。

为什么要将字符串Quotation传递到此函数getQuote("Quotation")?如果需要,可以将字符串"Quotation"传递给getQuote函数,如下所示。
这将为您的参数设置默认值,即使您没有向该函数调用传递任何内容。显然,您应该在这个函数中使用这个变量来获得字符串"Quotation"。

function getQuote(variable = "Quotation"){...}

我想您需要使用字符串作为变量来创建一个函数。所以你应该实现为

function getQuote(){ 
  var quotation="Quotation";
  return Math.floor(Math.random() * quotation.length); 
}
or
function getQuote(quotation){ 
  return Math.floor(Math.random() * quotation.length); 
}

在click方法中,您应该使用数组的名称(Quotation)而不是引号来引用数组。

$('#btn').click(
		function() {
			$('#quote').text(Quotation[getQuote()]);
		}
);

此外,请确保已将jQuery导入到html代码中。