【问题标题】:define function with object as argument以对象为参数定义函数
【发布时间】:2020-01-07 17:48:21
【问题描述】:

我需要定义一个函数 checkProperty(),它将使用作为参数传递的对象在 CodePen 的控制台中打印输出。

输出:如果属性 isForSale 等于 true,则控制台的预期输出应该是:所有者,John Doe 将房屋出售!该物业有 4 个设施。在另一种情况下,我们应该看到以下内容:Happy St no. 的家。 123不卖。

提前致谢。

对象:

let property = {
  owner: {
    firstName: "John",
    lastName: "Doe",
    age: 44
  },
  isForSale: true,
  sqrm: 120,
  address: {
    street: "Happy St",
    number: 123,
    city: "Miami",
    state: "FL",
    country: "US"
  },
  amenities: ["pool", "tennis court", "private parking", "yard"]
}

我做了什么:

checkProperty (someObj) {
  if(someObj.isForSale=true){
    console.log(`The owner, ${someObj.owner.firstName} ${someObj.owner.lastName} put the home for sale! The property has ${someObj.amenities.length} amenities`);
  }
  else {
    console.log(`The home is not for sale`);
  }
}


let property = {
  owner: {
    firstName: "John",
    lastName: "Doe",
    age: 44
  },
  isForSale: true,
  sqrm: 120,
  address: {
    street: "Happy St",
    number: 123,
    city: "Miami",
    state: "FL",
    country: "US"
  },
  amenities: ["pool", "tennis court", "private parking", "yard"]
}

checkProperty(property)

【问题讨论】:

  • = 应该是 =====

标签: javascript arrays object


【解决方案1】:

您好,我认为这可能是一个不错的解决方案。

// object
let property = {
  owner: {
    firstName: "John",
    lastName: "Doe",
    age: 44
  },
  isForSale: true,
  sqrm: 120,
  address: {
    street: "Happy St",
    number: 123,
    city: "Miami",
    state: "FL",
    country: "US"
  },
  amenities: ["pool", "tennis court", "private parking", "yard"]
}
//function

function checkProperty(obj){
  if(obj.isForSale){
    const {
      owner:{firstName,lastName},
      amenities
    }=obj;
    console.log(`The owner, ${firstName} ${lastName} put the home for sale! The property has ${amenities.length} amenities`);
  }
  else {
    const {
      address:{street,number},
    }=obj;
    console.log(`The home in ${street} on ${number} is not for sale`);
  }
}

checkProperty(property);

【讨论】:

    【解决方案2】:

    试试这个,我没有测试它,但它应该可以工作。

    function checkProperty(someObj) {
      if(someObj.isForSale){
        console.log(`The owner, ${someObj.owner.firstName} ${someObj.owner.lastName} put the home for sale! The property has ${someObj.amenities.length} amenities`);
      }
      else {
        console.log(`The home in ${someObj.address.street} on ${someObj.address.number} is not for sale`);
      }
    }
    

    【讨论】:

    • 解决了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多