0

Here is my code:

function getMelhorBloco(tamanho){

    var blocoMelhor = {};
    var testeEntrouBloco = true;

            for(var i = 0; i < $scope.blocos.length; i++) {
                if($scope.blocos[i].estado == "Livre") {

                    if(tamanho < $scope.blocos[i].tamanhoTotal) {
                        if(testeEntrouBloco) {
                            blocoMelhor.indice = $scope.blocos[i].idBloco;
                            blocoMelhor.tamanho = $scope.blocos[i].tamanhoTotal;
                            testeEntrouBloco = false;
                        } else {
                            if($scope.blocos[i].tamanhoTotal < blocoMelhor.tamanho) {
                                blocoMelhor.indice = $scope.blocos[i].idBloco;
                                blocoMelhor.tamanho = $scope.blocos[i].tamanhoTotal;

                            }
                        }
                    }
            }
        }

    return blocoMelhor;
}

I was trying to check if my object "blocoMelhor" is null.

I tried

if(blocoMelhor == null){} 
if(blocoMelhor == undefined){} 
if(blocoMelhor ===null){} 

and the method:

function isEmpty(obj){
    for(var key in obj) {
        if(obj.hasOwnProperty(key)){
            return false;
        }
        return true;
    }
}

I printed the value of "blocoMelhor" and the console gives me this: Object { }

Any suggestions?

Sam Hanley
  • 4,498
  • 7
  • 32
  • 56
F Matheus
  • 25
  • 1
  • 8
  • 1
    Why would you think that your object would be null? You're initializing it to `{}` - that's an empty object, but it's definitely not null or undefined. – Sam Hanley May 13 '16 at 17:52
  • `isEmpty(obj)` will never return false because `keys in obj` gets a list of keys, meaning that the object MUST contain each one –  May 13 '16 at 17:53
  • 1
    Possible duplicate of [How do I test for an empty JavaScript object?](http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object) – jmargolisvt May 13 '16 at 17:56

3 Answers3

1

try following

var blocoMelhor;

if(!blocoMelhor){ 
do something for null
} 

initialization by {} means you create a object

0

have you tried to use something like

if (!blocoMelhor){ //do something } 

? it's the best way, I think.

alvarosps
  • 83
  • 1
  • 9
0

i made the verification with the attributes of object and works:

var returnOfGetMelhorBloco = getMelhorBloco(tamanho);
if(returnOfGetMelhorBloco.indice == undefined){
//the object is null
} else {
//the object is not null
}
F Matheus
  • 25
  • 1
  • 8