gpt4 book ai didi

javascript - 最后一个值未存储在 Javascript 变量中

转载 作者:行者123 更新时间:2023-12-02 16:59:40 24 4
gpt4 key购买 nike

我正在关注 Dash 上的 Mad Lib 教程,但遇到了以下问题:

每当我运行以下代码时,它都应该将我的所有三个输入存储在数组 answers 中,但是,它不会存储最后一个。每当我使用 showFinal 输出 answers 数组时,它都会在第三个答案应该在的位置输出 undefinedHere是一个jsfiddle,输出同样的问题。

这是 JavaScript:

// List of prompts for the user
var prompts = [
'Type your name',
'Type an adjective',
'Type a noun'
];

var answers = [];
// Keep track of current prompt we're on
var currentPrompt = 0;

// A function that will call the next prompt
var nextPrompt = function() {
// if there is a next prompt
if (currentPrompt < prompts.length) {
if (currentPrompt != 0) {
answers.push($('input').val());
}
// put first prompt in all html elements with class
$('.prompt').html(prompts[currentPrompt] + '<br><input type="text">');
// move the next prompt into variable currentPrompt
currentPrompt = currentPrompt + 1;
}
//or else if we're at the end of the array
else {
// put a new message into the html.
showFinal();
}
}

var showFinal = function() {
$('.prompt').html(answers[0]+ ' ' + answers[1] + ' ' + answers[2]);
}

// run nextPrompt function when button is clicked
$('button').click(function() {
nextPrompt();
});

// Show the first prompt as soon as js loads
nextPrompt();

最佳答案

问题在于,在每一步单击“下一步”时,它都会在保存当前值之前检查是否有更多提示消息。但如果没有进一步的提示消息,它会跳到 showFinal()

您需要先推送当前值,然后再检查是否还有更多消息提示

if (currentPrompt != 0) {
answers.push($('input').val());
}
// if there is a next prompt
if (currentPrompt < prompts.length) {
....

更新了 fiddle :http://jsfiddle.net/w840jpac/1/

关于javascript - 最后一个值未存储在 Javascript 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25863102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com