Can I set variables to undefined or pass undefined as an argument?

后端 未结 10 1930
北荒
北荒 2020-11-30 15:53

I’m a bit confused about JavaScript’s undefined and null values.

What does if (!testvar) actually do? Does it test for u

10条回答
  •  孤街浪徒
    2020-11-30 16:33

    Just for fun, here's a fairly safe way to assign "unassigned" to a variable. For this to have a collision would require someone to have added to the prototype for Object with exactly the same name as the randomly generated string. I'm sure the random string generator could be improved, but I just took one from this question: Generate random string/characters in JavaScript

    This works by creating a new object and trying to access a property on it with a randomly generated name, which we are assuming wont exist and will hence have the value of undefined.

    function GenerateRandomString() {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
        for (var i = 0; i < 50; i++)
            text += possible.charAt(Math.floor(Math.random() * possible.length));
    
        return text;
    }
    
    var myVar = {}[GenerateRandomString()];
    

提交回复
热议问题