我正在尝试使用名称创建一个数组,然后使用for循环迭代它们,然后使用if else语句检查迭代。我的代码在下面,但它没有用,我没有看到结果。我尝试过,同样糟糕的结果。在Html文件中,我有一个带有演示ID的paraghraph和一个带迭代和检查数组
的函数的按钮function availableName() {
const check = document.getElementById('userID');
const takenNames=['manuel','remus','manuel-remus','tomi','mirel'];
const reservedNames=['cristina','angela','rusanda','costantin'];
const givenNames=[...takenNames, ...reservedNames];
for (givenName of givenNames) {
if (givenName === check) {
sayMessage=givenName +"Not available!";
}
else {
sayMessage= givenName +"Available";
}
}
document.getElementById("available").innerHTML= sayMessage;
};
答案 0 :(得分:1)
为什么不使用函数isInArray?
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
function availableName() {
const check = document.getElementById('userID');
const takenNames=['manuel','remus','manuel-remus','tomi','mirel'];
const reservedNames=['cristina','angela','rusanda','costantin'];
const givenNames=[...takenNames, ...reservedNames];
for (givenName of givenNames) {
if (isInArray(check, givenNames)) {
sayMessage=givenName +"Not available!";
}
else {
sayMessage= givenName +"Available";
}
}
document.getElementById("available").innerHTML= sayMessage;
};
答案 1 :(得分:1)
首先,您需要按照评论中的说明使用input
获取.value
的值。
然后要检查array
中是否存在,您可以使用 Array
的内置方法之一,例如 {{3 } 或 includes()
。
这应该是你的代码:
function availableName() {
const check = document.getElementById('userID').value;
const takenNames = ['manuel', 'remus', 'manuel-remus', 'tomi', 'mirel'];
const reservedNames = ['cristina', 'angela', 'rusanda', 'costantin'];
const givenNames = [...takenNames, ...reservedNames];
if (givenNames.indexOf(check) > 0) {
sayMessage = check + " Not available!";
} else {
sayMessage = check + " Available";
}
document.getElementById("available").innerHTML = sayMessage;
};
<强>演示:强>
这是一个演示:
function availableName() {
//const check = document.getElementById('userID').value;
const check = "cristina";
const takenNames = ['manuel', 'remus', 'manuel-remus', 'tomi', 'mirel'];
const reservedNames = ['cristina', 'angela', 'rusanda', 'costantin'];
const givenNames = [...takenNames, ...reservedNames];
if (givenNames.indexOf(check) > 0) {
sayMessage = check + " Not available!";
} else {
sayMessage = check + " Available";
}
document.getElementById("available").innerHTML = sayMessage;
};
availableName();
&#13;
<div id="available"></div>
&#13;