假设我有一个数组
arr = ["one", "two", "three"]
和逻辑
if "one" in arr
processOne()
if "two" in arr
processTwo()
if <<there is another items in array>>
processOthers()
lastif
中应该写什么条件?
我找到了 _.difference
函数,但我不想多次写入元素(“一”、“二”...)。
编辑
if else if else
不合适,因为我需要调用 0..N 个流程函数。- 这是数组的示例。但如果这段代码是对象,它会是什么样子呢?
- 数组没有重复项
最佳答案
通过使用.indexOf
方法。
var index;
if ( (index = arr.indexOf('one')) !== -1) {
processOne();
arr.splice(index, 1);
}
if ((index = arr.indexOf('two')) !== -1) {
processTwo();
arr.splice(index, 1);
}
if (arr.length > 0) {
processOthers();
}
更新:或者你可以循环数组。
var one = false, two = false, others = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === 'one' && !one) {
processOne();
one = true;
} else if (arr[i] === 'two' && !two) {
processTwo();
two = true;
} else (!others) {
processOthers();
others = true;
}
if (one && two && others) break;
}
关于javascript - 如何检查数组中剩余的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12139844/