var fruitsVeg = ["apple", "orange", "banana", "tomato", "onion"];
if(fruitsVeg包含"番茄"或"洋葱"或"番茄和洋葱")
alert("your array has only vegetables");
if(fruitsVeg包含" apple"或" orange"或" banana"或" apple和orange"或" apple和香蕉"或"橙和香蕉")然后
alert("your array has only fruits");
if(fruitsVeg仅包含来自水果的元素和仅来自蔬菜的元素,即var fruitsVeg = ["apple", "orange", "tomato", "onion"];
)
alert("your array has both fruits and vegetables");
答案 0 :(得分:2)
可读性优先示例:使用indexOf()
创建条件,例如:
var fruitsVeg = ["apple", "orange", "banana", "tomato", "onion"];
var isVege = fruitsVeg.indexOf("tomato") > - 1 || fruitsVeg.indexOf("onion") > -1
var isFruit = fruitsVeg.indexOf("orange") > - 1 || fruitsVeg.indexOf("apple") > -1 || fruitsVeg.indexOf("banana") > -1;
if(isVege && isFruit)
console.log("your array has both fruits and vegetables");
else if (isVege)
console.log("your array has only vegetables");
else if (isFruit)
console.log("your array has only fruits");

效果优先示例:如果bool
包含两种类型的植物,则在单个循环中为所有项目分配break
值,并fruitsVeg
分配var fruitsVeg = ["apple", "orange", "banana", "tomato", "onion"];
var isVege = false;
var isFruit = false;
function fruit(item) {
return item === "apple" || item === "banana" || item === "orange";
}
function vege(item) {
return item === "tomato" || item === "onion";
}
for(var i = 0; i < fruitsVeg.length; i++) {
var item = fruitsVeg[i];
if(isVege && isFruit) {
console.log("Both.");
break;
} else if (vege(item)) {
isVege = true;
} else if (fruit(item)) {
isFruit = true;
}
}
if( !(isVege && isFruit) ) {
if(isVege)
console.log("Vege");
else if(isFruit)
console.log("Fruit");
}
值: LoginManager.getInstance()
.logInWithReadPermissions(MainActivity.this,
new ArrayList<String>(AccessToken.getCurrentAccessToken().getDeclinedPermissions()) );
AddWithValue
&#13;
答案 1 :(得分:1)
var alert = console.log.bind(console) // for demo purposes
var fruitsVeg = ["apple", "orange", "banana", "tomato", "onion"];
var hasFruits = fruitsVeg.includes("tomato") || fruitsVeg.includes("onion")
var hasVeges = fruitsVeg.includes("apple") || fruitsVeg.includes("orange") || fruitsVeg.includes("banana")
if (hasFruits && hasVeges) alert("both fruits and vegetables")
else if (hasFruits) alert("only fruits")
else alert("only vegetables")
编辑:我想我也会尝试一个更高效的例子,因为为什么不呢!
var alert = console.log.bind(console) // for demo purposes
var fruitsVeg = ["apple", "orange", "banana", "tomato", "onion"];
var hasFruits = false,
hasVeges = false
if (fruitsVeg.some(function(e) {
if (/^(tomato|onion)$/.test(e)) hasVeges = true
else if (/^(apple|orange|banana)$/.test(e)) hasFruits = true
return hasFruits && hasVeges
})) {
alert('both fruits and vegetables')
} else {
alert(hasFruits ? 'only fruits' : 'only vegetables')
}