Declare variable value in function call

0

I do not know how to call this to search Google or if it is possible to do so. I have an object that looks like this:

var clear = {
    Search_r: false,
    Search_f: false,
    Search_e: false
}

And I have the following function

function clearSearch(clear) {
    if(clear.Search_r) {
        $(".search-r").html("")
    }
    if(clear.Search_f) {
        $(".search-f").html("")
    }
    if(clear.Search_e) {
        $(".search-e").html("")
    }
}

I call the function like this

    clear.Search_r = true
    clearSearch(clear)

It works fine, but I wanted to know how to pass true inside the function call and not the top line. Something like:

clearSearch(clear.Search_r = true) //isso não funciona e nem da erro

That is, it does not work, undefined . How would that be correct and if possible, how would you write this in Google to find other solutions?

    
asked by anonymous 23.10.2018 / 22:26

2 answers

2

The way your function is written, the parameter path you want to do is:

clearSearch({ Search_r: true })
    
23.10.2018 / 22:37
3

As you are using only one parameter of the Object, you do not have to pass it completely, just pass true or false to the function, for example:

function clearSearch(clear = true) {
  if (clear) {
    console.log("Limpa o console")
  } else {
    console.log("Ops")
  }
}

clearSearch(true)
clearSearch(false)
clearSearch()

If you need to pass the object, instead of funcao(obj.clear = true) , just use

function clearSearch(obj = {field1: true, field2: false}) {
    if(obj.field1) {
        console.log("Limpa o campo 1")
    } else {
      console.log("Ops 1")
    }
    
    if(obj.field2) {
        console.log("Limpa o campo 2")
    } else {
      console.log("Ops 2")
    }
}

clearSearch({field1:true,field2:true})
clearSearch({field2:false,field2:false})

clearSearch({field1:true,field2:false})
clearSearch({field2:false,field2:true})

clearSearch()

In addition to the above options, you can also use the Object.assign function. With this function you can set the default values of the object.

function clearSearch(obj) {
    obj = Object.assign({clear: true}, obj)

    if(obj.clear) {
        console.log("Limpa o console")
    } else {
      console.log("Ops")
    }
}

clearSearch({clear:true})
clearSearch({clear:false})

clearSearch()
clearSearch(false)
  

Note: The value you are trying to pass is an Object and not an Array

    
23.10.2018 / 22:35