简体   繁体   中英

define function with object as argument

I need to define a function checkProperty() that will use an object passed as an argument to print the output in the console on CodePen.

The output: if the property isForSale equals to true, the expected output to the console should be: The owner, John Doe put the home for sale! The property has 4 amenities.. In the other case, we should see the following: The home in Happy St no. 123 is not for sale.

Thanks in advance.

The 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"]
}

What I have done:

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)

Try this, I didn't test it but it should work.

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

Hello I think that maybe this can be a nice solution.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM