我有两个数组,想找到哪一个有变量:
var fruit = ["apple","banana","orange"];
var veggie = ["carrot","pea","corn"];
alert("An apple is a " + /*return array with value "apple"*/);
是否可以使用Javascript执行此操作?感谢
答案 0 :(得分:1)
在if / else语句中包含警报并检查'apple'的索引。如果fruit.indexOf('apple') != -1
那么它必须是一个水果。
答案 1 :(得分:0)
您可以使用如下所示的函数,并在每个相关的数组上调用它:
function contains(a, obj) { //a is the array to check, and obj the object you are looking for
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
答案 2 :(得分:0)
我会使用一个对象来包含各种类型:
var type = {
fruit: ["apple", "banana", "orange"],
veggie: ["carrot", "pea", "corn"]
}
如果你想找到数组的名称,那么东西就是在对象中的数组上循环,使用indexOf
来测试该东西的存在。
function findThing(thing) {
for (var k in type) {
if (type[k].indexOf(thing) > -1) return k;
}
return 'unknown';
}
console.log('An apple is a ' + findThing('apple')); // An apple is a fruit
console.log('An froom is a ' + findThing('froom')); // An froom is a unknown
另一方面,如果您想要返回更多信息(例如类型,大小和其他项目,您可以这样做:
function returnArrayOfThing(thing) {
for (var k in type) {
if (type[k].indexOf(thing) > -1) return k + ' which contains ' + type[k].length + ' items: ' + type[k];
}
return 'unknown';
}
console.log('An apple is in ' + returnArrayOfThing('apple')); // An apple is in fruit which contains 3 items: apple,banana,orange
答案 3 :(得分:0)
如果你只有两个类别,那么你可以做一个简单的检查:
var fruit = ["apple","banana","orange"];
var veggie = ["carrot","pea","corn"];
var typeOfApple = 'unknown';
if (fruit.indexOf('apple') !== -1) {
typeOfApple = 'fruit';
} else if (veggie.indexOf('apple') !== -1) {
typeOfApple = 'veggie';
}
alert("An apple is a " + typeOfApple);
如果您有更多类别(或者只是希望您的代码更加健壮),您可以使用带有键的对象作为类别,并使用该类别中的项目来表示数组:
var types = {
fruit : ["apple","banana","orange"],
veggie : ["carrot","pea","corn"]
}
然后,您可以检查每个类别是否包含您的项目:
var typeOfApple = 'unknown';
for (var type in types) {
if (types[type].indexOf('apple') !== -1)
typeOfApple = type;
}
alert("An apple is a " + typeOfApple);
答案 4 :(得分:0)
使用该对象包含这两个数组。
var food = {
fruit : ["apple","banana","orange"],
veggie : ["carrot","pea","corn"]
}
var arr = getFood('apple', food);
//returns ["apple","banana","orange"];
var arr2 = getFood('pea', food);
//returns ["carrot","pea","corn"];
function getFood(item, food){
for (var key in food){
if(food[key].indexOf(item) != -1){
return food[key];
}
}
}