【问题标题】:function that takes objects as parameters [duplicate]将对象作为参数的函数[重复]
【发布时间】:2019-03-30 15:12:17
【问题描述】:

我正在尝试编写一个将对象作为参数的函数,以测试是否有人满足或超过参数返回true,如果不返回false。我被困在如何正确地做到这一点上,我的搜索并没有让我走得更远。到目前为止我想出的是

var rollerCoaster = {
 age: a,
 height: b
 }

 if (age >= 7 && height >= 42) {
   return true;

 }else {
   return false;
 }
}
 rollerCoaster(age.2, height.13); 

【问题讨论】:

  • 你的语法看起来有点奇怪。你有函数头吗?过山车是对象还是函数?看这里:stackoverflow.com/questions/7764536/…
  • 我明白你在说什么,不,过山车不应该是一个函数。
  • @BrianGuta 不清楚你在问什么。如果rollerCoaster 不应该是一个函数,那么它是什么?你想要一个“带对象的函数”,但唯一看起来是函数的是rollerCoaster,那么你的函数在哪里?
  • 这个函数应该是检查一个人是否满足乘坐过山车的年龄和身高要求

标签: javascript object


【解决方案1】:

这是您想要的一种可能的(简单)解决方案:

const personOne = {
  age: 10,
  height: 45
}

const personTwo = {
  age: 1,
  height: 1
}



const checkRequirements = (age, height) => {
  if (age >= 7 && height >=42) {
    return true
  } 
  return false
}

console.log(checkRequirements(personOne.age, personOne.height)) // true
console.log(checkRequirements(personTwo.age, personTwo.height)) // false

【讨论】:

    【解决方案2】:

    简单易懂:

    function check(info){
      let age = info.age
      let height = info.height
    
      if (age >= 7 && height >= 42) {
         return true;
       }else {
         return false;
       }
    
    }
    check({age:53, height:150}) // true
    

    或单行:

    let check = (info)=> {return info.age >= 7 && info.height >= 42}
    
    check({age:53, height:150}) // true
    

    【讨论】:

    • 在这种情况下也可以使用解构赋值。 const f = ({ age = 0, height = 0 } = {}) => age >= 7 && height >= 42;
    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2016-10-16
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多