gpt4 book ai didi

javascript - 如何声明数组变量并将其与其他选定变量进行比较

转载 作者:行者123 更新时间:2023-11-28 11:36:27 25 4
gpt4 key购买 nike

我有

var two = document.getElementById('email').value;

我想将数组中的一些值与变量二中的值进行比较

email = two[gmail.com, yahoo.com]; // how to type this correctly

然后将电子邮件变量与用户插入的值进行比较,如果用户插入了数组中的值之一,则发送警报(“我们不接受免费电子邮件”)。

if email = 0 // did not found any of the values listed in email = then return true.

最佳答案

你是这个意思吗?

function validateEmail() {
var two = document.getElementById('email').value;
if (["gmail.com", "yahoo.com"].indexOf(two) != -1) {
alert("We don't accept free e-mail");
return false;
}
return true;
}

这将创建一个名为 validateEmail 的函数。它获取您的 email 元素,并检查固定数组以查看它是否包含该元素。如果是,它会发送您的警报并返回 false,否则返回 true。

尝试猜测您想要什么而不是您要求什么:

首先,您可能希望数组成为它自己的变量。这通常是一个很好的做法,可以让您更轻松地修改数组 - 或在其他地方创建它。

var badEmails = ["gmail.com", "yahoo.com"];
if (badEmails.indexOf(two) != -1) {

更重要的是,您可能需要检查用户输入的整个电子邮件地址。如果 two 是标准电子邮件,您的函数会变得稍微复杂一些:

function validateEmail() {
var two = document.getElementById('email').value;
var badEmails = ["gmail.com", "yahoo.com"];
for (var bad in badEmails) {
if (two.indexOf(bad) != -1) {
alert("We don't accept free e-mail");
return false;
}
}
return true;
}

关于javascript - 如何声明数组变量并将其与其他选定变量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19143834/

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