简体   繁体   English

尝试从 JavaScript 数组中删除 JSON 对象时收到错误消息

[英]Getting an error message when I try to remove a JSON object from a JavaScript Array

So I'm trying to build a relatively simple app that would take a group of 8 predetermined celebrities, display two at a time at random, and allow the user to pick which one they prefer until there is only one left.因此,我正在尝试构建一个相对简单的应用程序,该应用程序将包含 8 个预定名人,一次随机显示两个,并允许用户选择他们喜欢的一个,直到只剩下一个。 I've managed to get almost everything working correctly on the JavaScript side, but every once in a while I get an error message that can crash the application, and I can't figure out how to fix it.我已经设法让 JavaScript 端的几乎所有东西都能正常工作,但每隔一段时间我就会收到一条可能使应用程序崩溃的错误消息,我不知道如何修复它。 I'd really appreciate any help the community can provide.我非常感谢社区可以提供的任何帮助。

I've gone over the code looking for problems in logic that could be causing the error, and I've tried using console.logs to identify it, but the error seems to stop the console.logs themselves from displaying when it occurs.我已经检查了代码,寻找可能导致错误的逻辑问题,并且我尝试使用 console.logs 来识别它,但错误似乎阻止了 console.logs 本身在它发生时显示。

You can find the GitHub repository here:您可以在此处找到 GitHub 存储库:

https://github.com/jesberman/Celeb-Mash-Prototype https://github.com/jesberman/Celeb-Mash-Prototype

And the live site (with errors) here:和现场网站(有错误)在这里:

https://jesberman.github.io/Celeb-Mash-Prototype/ https://jesberman.github.io/Celeb-Mash-Prototype/

An important part of the code is organized as a series of if statements, which I'll display below:代码的一个重要部分被组织为一系列 if 语句,我将在下面显示:

if(initialPicValue1 === initialPicValue2 && initialPicValue2 === celebArrayLength){
    initialPicValue2 -= 1;
}
if (initialPicValue1 === initialPicValue2){
    initialPicValue2 += 1;
}
if(initialPicValue1 === initialPicValue2 && initialPicValue1 === 0){
    initialPicValue2 += 1;
}
if (celebArrayLength === 1){
    return alert("Congrats! Your Favorite Celeb is " + celebArray[0].name);
}

I'm looking to get through all of the objects in the array cleanly without any problems, until only one is left.我正在寻找干净地通过数组中的所有对象而没有任何问题,直到只剩下一个。 However, I sometimes will randomly get the following error:但是,我有时会随机收到以下错误:

Uncaught TypeError: Cannot read property 'picture' of undefined at pressButton1 (logic.js:128) at HTMLButtonElement.onclick (index.html:21)未捕获的类型错误:无法在 HTMLButtonElement.onclick (index.html:21) 的 pressButton1 (logic.js:128) 处读取未定义的属性“图片”

I can see that you are getting an error on the line:我可以看到您在线上收到错误消息:

console.log(celebArray[initialPicValue2].picture);

The problem is that you have an array of celebrities, celebArray , and when you click one of the buttons you are accessing an index within that array.问题是您有一个名人数组celebArray ,当您单击其中一个按钮时,您正在访问该数组中的索引。 The error happens when you get down to only one celebrity left in the array, it tries to access an index that isn't there.当数组中只剩下一个名人时会发生错误,它会尝试访问不存在的索引。 So to avoid the error you have to take the first block of code in the pressButton function before if (celebArrayLength === 1) and put it in an if statement of:因此,为了避免错误,您必须在if (celebArrayLength === 1)之前获取pressButton函数中的第一个代码块,并将其放入以下if语句中:

if (celebArray.length > 1) {
  // do something
}

And then when it runs if (celebArrayLength === 1) and finds there is only one celebrity remaining you could hide the buttons by doing the following because now the game is over.然后当它运行if (celebArrayLength === 1)并发现只剩下一个名人时,您可以通过执行以下操作来隐藏按钮,因为现在游戏结束了。

if (celebArrayLength === 1) {
  $('button').hide()
  return alert("Congrats! Your Favorite Celeb is " + celebArray[0].name);
}

In your code you have a function for each button but I've simplified it so now there is the one function that gets run for both buttons and you pass in the number of the button like so <button id="button1" onclick="pressButton(1)"> and then you have a function like this function pressButton(e) .在您的代码中,每个按钮都有一个函数,但我已经对其进行了简化,因此现在有一个函数可以同时运行两个按钮,您可以像这样传入按钮的编号<button id="button1" onclick="pressButton(1)">然后你有一个像这个function pressButton(e)

So then in that function it has the number of the button in the variable e and you can get the number of the other button by removing e from an array [1,2] and then using the remaining number:因此,在该函数中,它具有变量e中的按钮编号,您可以通过从数组[1,2]删除e然后使用剩余数字来获取另一个按钮的编号:

var arr = [1,2] // a list with the numbers of the buttons
arr.splice(e-1, 1) // we remove the one that was pressed
var other = arr[0] // the one left is the other one

I tidied up a few other things like that.我整理了一些其他类似的东西。 Hopefully you can see what I've done.希望你能看到我所做的。 It's generally better to not duplicate functions so that it's easier to just edit one function when you want to change something, and then you don't have to worry about forgetting to do it to both.通常最好不要重复函数,这样当您想要更改某些内容时,只需编辑一个函数会更容易,然后您就不必担心忘记对两个函数都执行此操作。

So this is my version which fixes your problem.所以这是我的版本,可以解决您的问题。 I've linked the images to where they are online, but I've kept the relative links but just commented.我已将图像链接到它们的在线位置,但我保留了相关链接但只是发表了评论。

 var celebArray = [ { name: "Tom Hanks", // picture: "assets/images/tomHanks.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/tomHanks.jpg" }, { name: "Benedict Cumberbatch", // picture: "assets/images/benedictCumberbatch.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/benedictCumberbatch.jpg" }, { name: "Charlize Theron", // picture: "assets/images/charlizeTheron.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/charlizeTheron.jpg" }, { name: "Evangeline Lilly", // picture: "assets/images/evangelineLilly.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/evangelineLilly.jpg" }, { name: "Katee Sackhoff", // picture: "assets/images/kateeSackhoff.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/kateeSackhoff.jpg" }, { name: "Robert Downey Jr.", // picture: "assets/images/robertDowneyJr.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/robertDowneyJr.jpg" }, { name: "Rose Leslie", // picture: "assets/images/roseLeslie.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/roseLeslie.jpg" }, { name: "Denzel Washington", // picture: "assets/images/denzelWashington.jpg" picture: "https://jesberman.github.io/Celeb-Mash-Prototype/assets/images/denzelWashington.jpg" }, ]; function picValues() { var initialPicValues = {} celebArrayLength = celebArray.length; initialPicValues[1] = Math.floor((Math.random() * celebArrayLength)); var keys = Object.keys(celebArray) keys.splice(initialPicValues[1], 1) var rnd_2 = Math.floor((Math.random() * keys.length)); initialPicValues[2] = keys[rnd_2] return initialPicValues } var celebArrayLength = celebArray.length; var initialPicValues = picValues(celebArray) function loadPics() { $("#picture1").css("background-image","url(" + celebArray[initialPicValues[1]].picture + ")"); $("#picture2").css("background-image","url(" + celebArray[initialPicValues[2]].picture + ")"); } loadPics(); console.log("Initial Array:"); console.log(celebArray); function pressButton(e) { if (celebArrayLength > 1) { var arr = [1,2] // a list with the numbers of the buttons arr.splice(e-1, 1) // we remove the one that was pressed var other = arr[0] // the one left is the other one console.log("Initial Pic "+other+" Value"); console.log(initialPicValues[other]); console.log("Celeb Being Removed"); console.log(celebArray[initialPicValues[other]].picture); celebArray.splice(initialPicValues[other], 1); initialPicValues = picValues(celebArray) } if (celebArrayLength === 1) { $('button').hide() return alert("Congrats! Your Favorite Celeb is " + celebArray[0].name); } console.log("Celeb To Be Removed:") console.log(celebArray[initialPicValues[other]].picture); console.log('celebArrayLength', celebArrayLength) loadPics() console.log("Array After Button Press:"); console.log(celebArray); }
 #main-div { padding-top: 50px; padding-right:10%; padding-left: 10%; background-color: gold; width: 100%; height: 700px; } #header-div { text-align: center; background-color: green; height: 100px; width: 80%; } #left-div { display: inline-block; background-color: red; width: 40%; height: 400px; } #picture1 { background-repeat: no-repeat; width: 100%; height: 300px; } #button1 { position: relative; left: 40%; } #right-div { display: inline-block; background-color: blue; width: 40%; height: 400px; } #picture2 { background-repeat: no-repeat; width: 100%; height: 300px; } #button2 { position: relative; left: 40%; }
 <!DOCTYPE html> <head> <title> Celeb Mash </title> <link rel="stylesheet" href="assets/css/style.css"> <script src="https://code.jquery.com/jquery.js"></script> </head> <body> <div id="main-div"> <div id="header-div"> <h2> Pick The Celeb You Like More </h2> </div> <div id="left-div"> <div id="picture1"> </div> <button id="button1" onclick="pressButton(1)"> Submit </button> </div> <div id="right-div"> <div id="picture2"> </div> <button id="button2" onclick="pressButton(2)"> Submit </button> </div> </div> <!-- <script src="assets/javascript/logic.js"> --> </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试使用“.remove()”时出现错误 - Getting an error when I try to use ".remove()" 从 json 阵列 javascript 中删除整个 object - Remove entire object from a json array javascript 当我尝试从这个 JSON 文件中获取信息时,为什么会出现语法错误? - Why am I getting a syntax error when I try to take info from this JSON file? 当我尝试在JavaScript中解析JSON时为什么会出错 - Why I get error when I try to parse JSON in the JavaScript 当我尝试解析数据以从 JSON 获取值时出现错误 - Getting an error when I try to parse data to get values from JSON 当我尝试使用ajax post将值从JavaScript发送到PHP时获取Error值 - Getting Error value when I try to send value from JavaScript to PHP with ajax post 尝试从 JavaScript 中的 localStorage 查找现有产品时出错 - Getting error when try to find existing product from localStorage in JavaScript 尝试制作Javascript对象时出现未引用的错误 - Uncaught reference error when I try and make a Javascript object 从 javascript 中的 JSON object 中删除特定数组元素 - Remove specific array element from JSON object in javascript 删除功能 <span></span> 从JavaScript中的json对象数组中的字符串 - Function to remove <span></span> from string in an json object array in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM