首页 > 解决方案 > 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

随时为我的代码添加一般建议/改进,我是一个新手

标签: javascripthtmltypeerror

解决方案


谢谢您的帮助!我认为调用错误的原因是由于事件目标(单击目标)是 SVG 内部的多边形而不是整个 svg 元素。

这可以通过将 console.log(e.target) 添加到我的 doRound() 函数中来观察。

现在找到一种方法来“分组”svg,这样点击里面的任何地方都会触发整个 SVG 元素。


推荐阅读