用对象作为参数定义函数

时间:2019-09-04 19:58:03

标签: javascript arrays object

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

输出:如果属性isForSale等于true,则控制台的预期输出应为:所有者John Doe将房屋出售!该物业有4个便利设施。 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)

2 个答案:

答案 0 :(得分:0)

尝试一下,我没有测试,但是应该可以。

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

答案 1 :(得分:0)

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

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