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

标签 javascript jquery

因此,我正在尝试构建一个相对简单的应用程序,该应用程序将包含一组 8 位预先确定的名人,一次随机显示两个,并允许用户选择他们喜欢的一个,直到只剩下一个。我已经设法让几乎所有的东西都在 JavaScript 端正常工作,但每隔一段时间我就会收到一条可能导致应用程序崩溃的错误消息,而且我不知道如何修复它。我非常感谢社区可以提供的任何帮助。

我检查了代码以寻找可能导致错误的逻辑问题,并且我尝试使用 console.logs 来识别它,但错误似乎阻止了 console.logs 本身在它出现时显示发生。

您可以在此处找到 GitHub 存储库:

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

实时站点(有错误)在这里:

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

代码的一个重要部分被组织为一系列 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);
}

我希望能够毫无问题地彻底遍历数组中的所有对象,直到只剩下一个。但是,我有时会随机得到以下错误:

未捕获的类型错误:无法读取未定义的属性“图片” 在 pressButton1 (logic.js:128) 在 HTMLButtonElement.onclick (index.html:21)

最佳答案

我可以看到您在线上遇到错误:

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

问题是你有很多名人,celebArray ,并且当您单击其中一个按钮时,您正在访问该数组中的索引。当数组中只剩下一位名人时会发生错误,它会尝试访问不存在的索引。因此,为避免错误,您必须采用 pressButton 中的第一段代码。 if (celebArrayLength === 1) 之前的功能并将其放入 if声明:

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

然后当它运行时if (celebArrayLength === 1)并发现只剩下一位名人,您可以通过执行以下操作来隐藏按钮,因为现在游戏结束了。

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

在您的代码中,每个按钮都有一个函数,但我已经简化了它,所以现在有一个函数可以同时运行两个按钮,您可以像这样传递按钮的编号 <button id="button1" onclick="pressButton(1)">然后你有一个像这样的功能 function pressButton(e) .

那么在那个函数中它有变量e中的按钮编号。您可以通过删除 e 来获取另一个按钮的编号来自数组 [1,2]然后使用剩余的数字:

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

我整理了一些类似的东西。希望你能看到我做了什么。通常最好不要重复函数,这样当您想要更改某些内容时只编辑一个函数会更容易,然后您就不必担心忘记对两个函数都进行编辑。

这是我的版本,可以解决您的问题。我已将图片链接到它们的在线位置,但我保留了相关链接但只是评论了。

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>

关于javascript - 当我尝试从 JavaScript 数组中删除 JSON 对象时收到错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57103327/

相关文章:

javascript - 从自定义方法调用 jquery validator 的核心方法

jquery - 正则表达式惰性量词表现得贪婪

javascript - 如何让 PHP 验证回退?

javascript - 为什么 javascript 会改变 Array.push 上的数据类型?

javascript - 如何从 Javascript 创建 Bootstrap 弹出窗口?

javascript - 在javascript中同步执行函数

jquery .不是第一个或最后一个

javascript - 标记之间的折线动画 - Mapbox

javascript - 如何在不禁用 JQuery 按钮的情况下停止表单提交?

javascript - Rails Javascript haml 变量创建