简体   繁体   中英

How to return multiple values of an array in javascript

Here I am able to return one value return fruit === 'cherries' , how can I return two values , such as I tried return [fruit==='cherries', fruit==='bananas'] , How can I return two values.

var inventory = ['apples','bananas','cherries'];
function findCherries(fruit) { 
  return fruit === 'cherries'  ;
}
console.log(inventory.find(findCherries));

You could use a logical OR -> || and Array.filter

 var inventory = ['apples', 'bananas', 'cherries']; function findCherries(fruit) { return fruit === 'cherries' || fruit === 'bananas'; } console.log(inventory.filter(findCherries));

You could fiter it with an array of the wanted items.

 function findFruits(fruits) { return fruit => fruits.includes(fruit); } var inventory = ['apples', 'bananas', 'cherries']; console.log(inventory.filter(findFruits(['bananas', 'cherries'])));

If your inventory is below and u know which one is fruit then

function findMyInventory(type) {
  var inventory = ['apples', 'bananas', 'cherries', 'beans', 'roots'];

  var list = [];
  if ( type == 'fruits') {
    list.push(inventory.slice(0,2) );
  }  else if ( type == 'vegetables' ) {
    list.push( inventory.slice(3,4) ) ; 
  }

  return list;
}

if your list as below

var inventory = [
  { type: 'fruit' , name : 'apples'},
  { type: 'fruit' , name : 'bananas'},
  { type: 'fruit' , name : 'cherries'},
  { type: 'vegetable' , name : 'beans'},
  { type: 'vegetable' , name : 'roots'}
];

function findMyInventory(type) {
  var myList = [];
  for ( var item of inventory) {
    if ( type == item.type) {
       myList.push( item);
    }
  }
  return myList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM