gpt4 book ai didi

javascript - 使用文本文件而不是数组?

转载 作者:行者123 更新时间:2023-11-28 06:15:10 26 4
gpt4 key购买 nike

我对 Javascript 还很陌生,我想知道是否可以使用上传的 .txt 文件或 .csv 文件来替换以下数组;

我想使用 .txt 的原因。或 .csv 文件是因为实际上我每天都会收到数百个邮政编码,并更新邮政编码或删除邮政编码(如果它们超过 90 天)。我不想每天编辑数组。

    if (isInArray(pcode, [2000, 2001, 2100, 2010, 3100, 3131, 3123, 3333, 3215, 4100, 4321, 4567, 4865, 5000]) !== -1) {
pcheck = "Delivered";
} else {
pcheck = "Not delivered";
}

这是整个代码:

<!DOCTYPE html>
<html>
<body>

Enter the Post Code:

<input id="code" value="" />

<button onclick="validate()">Submit</button>

<p id="result"></p>
<p id="state"></p>

<script>
function isInArray(value,array) {
return array.indexOf(value) > -1;
}

function validate() {
var pcode, pcheck, pstate;
pcode = Number(document.getElementById("code").value);
if (isNaN(pcode)) {
pcheck = "This is not a post code.";
pstate = "No state.";
}

if (isInArray(pcode, [2000, 2001, 2100, 2010, 3100, 3131, 3123, 3333, 3215, 4100, 4321, 4567, 4865, 5000]) !== -1) {
pcheck = "Delivered";
} else {
pcheck = "Not delivered";
}

if (((pcode >= 2000) && (pcode <= 2599))||((pcode >= 2619) && (pcode <= 2899))||((pcode >= 2921) && (pcode <= 2999))) {
pstate = "NSW";
} else if ((pcode >= 1000) && (pcode <= 1999)) {
pstate = "NSW LVR/PO Box";
} else if (((pcode >= 2600) && (pcode <= 2618))||((pcode >= 2900) && (pcode <= 2920))) {
pstate = "ACT";
} else if ((pcode >= 200) && (pcode <= 299)) {
pstate = "ACT LVR/PO Box";
} else if ((pcode >= 3000) && (pcode <= 3999)) {
pstate = "VIC";
} else if ((pcode >= 8000) && (pcode <= 8999)) {
pstate = "VIC LVR/PO Box";
} else if ((pcode >= 4000) && (pcode <= 4999)) {
pstate = "QLD";
} else if ((pcode >= 9000) && (pcode <= 9999)) {
pstate = "QLD LVR/PO Box";
} else if ((pcode >= 5000) && (pcode <= 5799)) {
pstate = "SA";
} else if ((pcode >= 5800) && (pcode <= 5999)) {
pstate = "SA LVR/PO Box";
} else if ((pcode >= 6000) && (pcode <= 6797)) {
pstate = "WA";
} else if ((pcode >= 6800) && (pcode <= 6999)) {
pstate = "WA LVR/PO Box";
} else if ((pcode >= 7000) && (pcode <= 7799)) {
pstate = "TAS";
} else if ((pcode >= 7800) && (pcode <= 7999)) {
pstate = "TAS LVR/PO Box";
} else if ((pcode >= 800) && (pcode <= 899)) {
pstate = "NT";
} else if ((pcode >= 900) && (pcode <= 999)) {
pstate = "NT LVR/PO Box";
} else {
pcheck = "This is not a post code.";
pstate = "No state.";
}

document.getElementById("result").innerHTML = pcheck;
document.getElementById("state").innerHTML = pstate;
}
</script>

</body>
</html>

任何有关如何简化此操作的建议都很棒。再说一遍,我对 JS 很陌生,所以任何帮助都会很棒!

最佳答案

如果你涉及到服务器,那么你就有很多选择。

我能想到的最简单的方法来完成你所要求的,这似乎是在加载到浏览器中后解析文本或csv文件,将是:

(1) 对文本文件发出 AJAX 请求,对于 Javascript 新手来说,最简单的方法可能是 jQuery.get()

(2) .txt 文件只是一个字符串,因此您可以这样做:

var lines = file.split('\n');

lines 将是一个数组,您可以在示例中根据需要进行处理。

关于javascript - 使用文本文件而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36047736/

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