我正在尝试使用Javascript,尝试从数组参数中获取长度时得到了意外的空引用。为什么此代码不起作用?
这是错误消息:无法获取未定义或空引用的属性“ length”
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>Phrase-o-matic</h2>
<div id="example"></div>
</body>
<script>
document.write(GetRandomWord(words1) + " " + GetRandomWord(words2) + " " + GetRandomWord(words3));
var words1 = ["24/7", "multi-tier", "30 000 foot", "B-to-B", "win-win"];
var words2 = ["empowered", "value-added", "oriented", "focused", "aligned"];
var words3 = ["process", "solution", "tipping-point", "strategy", "vision"];
function GetRandomWord(wordArray){
var rand = Math.floor(Math.random()) * wordArray.length;
var randomWord = wordArray[rand];
return randomWord;
}
</script>
</html>
答案 0 :(得分:0)
正如其他人所述,必须在数组声明后移动document.write
。
顺便说一句,您的随机生成代码也不起作用。改用它:
var rand = Math.floor(Math.random() * (wordArray.length - 1) + 1);
其中1
是最小值,wordArray.length
是最大值。