【发布时间】:2019-10-16 15:23:54
【问题描述】:
伙计们,我有一个 JavaScript 函数,它应该返回一个带有值的数组。这是函数:
let finalInput;
let input;
function getCorrectInput (input, finalInput) {
input = prompt("Type the client type followed by" +
"semicollon and the dates separated by comma"+
"(Following the example: Reward: 31Dez2019(weekday), 01Jan2020(weekday)):");
while (input === undefined || input === null || input === '') {
input = prompt("Type the client type followed by" +
"semicollon and the dates separated by comma"+
"(Following the example: Reward: 31Dez2019(weekday), 01Jan2020(weekday)):");
}
if (input)
return
finalInput = input.split(',');
return finalInput
}
getCorrectInput()
基本上,该函数验证字段是否包含某些内容(如果用户键入)并返回输入中的内容。所以函数的输出应该是这样的:
finalInput = ["Reward", "date1", "date2"]
我需要访问位置 [0] 处的 finalInput,并将其传递给一个变量,如下所示:
const clientType = finalInput[0]
但是当我尝试访问 finalInput 时,它返回一个错误,指出它无法读取未定义的属性 0。所以这意味着代码没有返回带有值的数组。
我做错了什么?
【问题讨论】:
-
prompt在while循环中是一个糟糕的选择;我很想将它从问题中完全删除,因为你不能“取消”它。也就是说,if (input) return... 如果input是任何真实值,这将退出函数。 -
我看到
return没有分号,这是一个基本问题。我想知道,我需要进一步阅读吗?请注意,return后跟换行符会解析为return;。 -
条件
if (input)是没有意义的,在你循环之后这个条件总是true和return退出函数,返回undefined -
semicollon可能想检查您的拼写
标签: javascript arrays function