问题如下:
validItems(items) – 此函数接收要提供给客户的项目的字符串数组。函数返回一个空字符串,表示数组中的所有项目代码都有效;否则该函数返回数组中第一个无效的项目代码。所有商品代码必须从提供的商品代码中选择。它们是:IT00、O144、6A1L、4243、O3D5、44SG、CE64、54FS 和 4422。
这是我到目前为止所做的:
function validItems(items) {
var error = false;
for (i = 0; i < items.length; i++) {
if (error == false) {
if (items[i] != "IT00" ||
items[i] != "0144" ||
items[i] != "6A1L" ||
items[i] != "4243" ||
items[i] != "O3D5" ||
items[i] != "44SG" ||
items[i] != "CE64" ||
items[i] != "54FS" ||
items[i] != "4422") {
error = items[i];
} else {
error = false;
}
} else {
if (error != false) {return error;} else {return "";}
}
}
}
var items = ["IT00","0144","6A1L"];
alert(validItems(items));
它不断返回 IT00。我做错了什么?
最佳答案
您会注意到这里的复杂性为零。下面的每个函数都接受几个参数并执行一个简单的任务。乍一看很容易看出每个函数的作用。
// your data
const validItems = [
"0144", "6A1L", "4243", "O3D5", "44SG", "CE64", "54FS", "4422"
];
// some reusable functions
const all = f => xs => xs.every(f);
const comp = f => g => x => f(g(x));
const neq = y => x => x !== y;
const indexOf = xs => x => xs.indexOf(x);
const elem = xs => comp(neq(-1))(indexOf(xs))
// your helpers
const validateItems = all(elem(validItems));
// test it out
console.log( validateItems(["0144", "6A1L"]) ); // true
console.log( validateItems(["0144", "CAKE"]) ); // false
关于验证数组内容的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30973197/