Javascript - what thing in var

I have either a literal object or one of its components in var Z. i.e. one of the following

var Q = {"name" : 123};

Z = Q; 
Z = Q["name"];

How can I determine what it is?

0
source share
4 answers

In this case, you can use typeof [ mozilla docs ] to check if this value is a number or not.

if (typeof z === "number") {
    alert("I'm the property!");
} else {
    alert("I'm the object!");
}

typeof xuseful if xa primitive "number", "boolean", "string", "undefined"or "function", but you need a more sophisticated test for other types.

, , - . patrick dw , .

+4

, typeof , [[Class]], Object.prototype.toString Z , :

var type = Object.prototype.toString.call( Z );  // [object ???]

[object Class], :

[object Object]
[object Array]
[object Number]
[object Boolean]
[object String]

, - :

function getType( x ) {
    return x === void 0 ? 'undefined' :
           x === null ? 'null' :
           Object.prototype.toString.call( x ).slice( 8, -1 ).toLowerCase();
}

:

"string"
"number"
"array"
// ...etc

null undefined, , , . , .

, :

if( getType( Z ) === "string" ) {
    // do something
} else {
    // do something else
}

, , , , , , typeof "object" "string".

typeof new String("test");  // "object"

, Array, "object" typeof.

+2

typeof

Z = Q; 
typeof Z == "object"; //true
Z = Q["name"];
typeof Q == "number"; //true
0

, , "typeof" - , .

, typeof , undefined boolean, , .

0
source

Source: https://habr.com/ru/post/1618698/


All Articles