I made a code that get a type of inputs.All of the inputs that i add to the function have there correct answers (ex:prompt(10) result is : Number). when i tried to add object like this({}) i get Undefined the code that i made is :
function type() {
var Input = eval (prompt("please enter a value"));
var Primitive = [Boolean(Input), String(Input), null, undefined,
Number(Input)];
for (i = 0; i < Primitive.length; i++) {
if (Primitive[i]) {
console.log (typeof Input)
}
}
}
type();
I tried to use instanceof but i get the same result for object which is undefined.
The Expected result when i prompt {} i get Object. note: for Array [] i get object no problem in it .
答案 0 :(得分:2)
if you use eval({})
Javascript will treat {} as an empty block, not an object. I (and many developers) highly disencourage the use of eval()
you can escape this using eval("(" + prompt("please enter a value") + ")");
Here's the difference:
var Input = eval (prompt("please enter a value"));
// if you type {} this will turn into eval({}) wich is the same as eval() which will return "undefined"
Input = eval("(" + prompt("please enter a value") + ")");
//Typing {} will turn into eval(({})) wich makes {} an expression instead of an empty block. thus returning "object"
答案 1 :(得分:1)
{}
gets interpreted as an (empty) block of code, not an object literal. It has no return value, so it defaults to undefined
.
You'd get the same results if you entered ;
.
To get an actual object, you need to make sure {
is interpreted as part of an expression, not the beginning of a statement, for example by using ({})
.