【问题标题】:How can I create an array with return result of a function?如何创建具有函数返回结果的数组?
【发布时间】:2018-06-27 04:51:25
【问题描述】:

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

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()) 但它不起作用,我不知道为什么......

【问题讨论】:

  • function tipCal() 不返回任何内容

标签: javascript


【解决方案1】:

要创建tips,使用.map 会更合适,为此,您需要一个returns 计算提示的函数:

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);

【讨论】:

    【解决方案2】:

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

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 2012-09-26
      • 2012-01-01
      • 1970-01-01
      相关资源
      最近更新 更多