如何使用函数的返回结果创建数组?

时间:2018-06-27 04:51:26

标签: javascript

我创建了一个简单的计算器

johnRestBill = [124, 48, 268, 180, 42]; //dollar

function tipCal(){
  for(var i = 0; i < johnRestBill.length; i++){
  if (johnRestBill[i] < 50) {
    console.log(johnRestBill[i] * .2);
  } else if (johnRestBill[i] >= 50 && johnRestBill[i] <= 200){
    console.log(johnRestBill[i] * .15);
  } else {
    console.log(johnRestBill[i] * .1);
  }
 }
}
return tipCal();

我得到了johnRestBill数组的每个索引的结果,现在我想用结果创建一个数组。 所以我做了var tips = []并键入了tips.push(tipCal()),但是它不起作用,我也不知道为什么...

2 个答案:

答案 0 :(得分:1)

要创建tips,改用.map更合适,为此,您需要一个return s计算出的吸头的函数:

const johnRestBill = [124, 48, 268, 180, 42];

function tipCal(bill) {
  if (bill < 50) return bill * .2;
  else if (bill >= 50 && bill <= 200) return bill * .15;
  else return bill * .1;
}
const tips = johnRestBill.map(tipCal);
console.log(tips);

答案 1 :(得分:1)

您可以使用数组映射方法并返回相同的逻辑条件

var johnRestBill = [124, 48, 268, 180, 42]; //dollar
// map returns a new array 
let arr = johnRestBill.map(function(item) {
  if (item < 50) {
    return item * .2;
  } else if (item >= 50 && item <= 200) {
    return item * .15;
  } else {
    return item * .1;
  }
})
console.log(arr)

相关问题