javascript - JS Uncaught TypeError:无法读取未定义的属性(vanilla js)
问题描述
我为此失去了毛囊=)
所以我正在为石头剪刀布页面制作 UI;一切正常,除了随机奇怪的控制台错误。
我有一个逻辑函数、一个随机计算机选择函数和一个事件监听器。
我正在努力做到这一点,因此单击图标(svg)会调用逻辑函数来处理谁赢了。
它工作正常,50% 的时间。我根本找不到引发错误的模式。提前致谢。
//rock paper scissor game..
//helper dictionaries for functions
const mapState = {0:"draw", 1:"win", 2:"loss"};
const mapChoices = {"rock":0, "paper":1, "scissor":2}
//function responible for computer choice
function randomizer() {
let choices = ["rock", "paper", "scissor"];
//chooses a random decimal from 0(inclusive) to 1(exclusive)
randomDecimal = Math.random();
//changes the random to 0/1/2
randomChoice = Math.floor(randomDecimal*3);
//finds the tool associated with the number choosen, and prints it.
let computerChoice = choices[randomChoice];
console.log(computerChoice);
//return the random number (0/1/2)
return randomChoice;
}
//game logic determining win, loss, draw.
function logic(humanInput, computerChoice) {
const arrayMatrix = [[0, 2, 1],
[1, 0, 2],
[2, 1, 0]];
let result = arrayMatrix[humanInput][computerChoice];
console.log("logic result: " + result);
return result;
}
//hardcoded game length
function roundsCount() {
return 5;
}
//the DOM variables:
let tools = document.querySelectorAll(".tool");
let rock = document.querySelector("#rock");
let paper = document.querySelector("#paper");
let scissor = document.querySelector("#scissor");
let divOutput = document.querySelector("#score");
function doRound(e){
let humanChoice = mapChoices[e.target.id]
let randomChoice = randomizer();
let result = logic(humanChoice, randomChoice);
console.log("doround result: " + result);
return result;
}
divOutput.innerText = "Choose Your Weapon!"
tools.forEach(tool => {
tool.addEventListener('mouseover', event => {
tool.classList.add("selected");
});
tool.addEventListener('mouseout', event => {
tool.classList.remove("selected");
});
tool.addEventListener('click', doRound);
});
浏览器确定问题出在我的 logic() 函数上,特别是在let result = arrayMatrix[humanChoice][coputerChoice]
部分
我的代码:https ://codepen.io/sirbecalo/pen/KKqggEO
随时为我的代码添加一般建议/改进,我是一个新手
解决方案
谢谢您的帮助!我认为调用错误的原因是由于事件目标(单击目标)是 SVG 内部的多边形而不是整个 svg 元素。
这可以通过将 console.log(e.target) 添加到我的 doRound() 函数中来观察。
现在找到一种方法来“分组”svg,这样点击里面的任何地方都会触发整个 SVG 元素。
推荐阅读
- javascript - 如果秒数是 3 的倍数,则打印 fuzz
- authentication - 匹配提供和原始服务时的 CAS "INVALID_SERVICE" 异常(两者相同)
- javascript - 无法在 phonegap 上发送短信 - 没有权限
- qt - QML如何强制更新/重绘
- tensorflow.js - 为什么在 tensorflow.jsposenet 的响应中,位置 x 和 y 都为 0?
- java - 如何在 Java 应用程序中维护 xsd 文件(ddex 规范)的增量版本?
- ios - 如何从 UITableView 部分获取选定的 UISwitch 标签?
- javascript - 使用相同的类 jQuery 在单击事件上仅显示一个打开的 DIV
- python - 如何使用 Pandas python 仅显示来自 csv 文件的列的头部
- python - 如何处理熊猫数据框中的列?