Javascript 为什么在获取输入类型的函数中输入{}时未定义
我编写了一个代码来获取一种类型的输入。我添加到函数中的所有输入都有正确的答案(例如:prompt(10)result是:Number)。当我尝试添加类似({})的对象时,我得到了未定义的代码:Javascript 为什么在获取输入类型的函数中输入{}时未定义,javascript,Javascript,我编写了一个代码来获取一种类型的输入。我添加到函数中的所有输入都有正确的答案(例如:prompt(10)result是:Number)。当我尝试添加类似({})的对象时,我得到了未定义的代码: function type() { var Input = eval (prompt("please enter a value")); var Primitive = [Boolean(Input), String(Input), null, undefined, Number(Input
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();
函数类型(){
var Input=eval(提示(“请输入值”);
var Primitive=[Boolean(输入),String(输入),null,未定义,
数字(输入)];
对于(i=0;i
我尝试使用instanceof,但对于未定义的对象,我得到了相同的结果
提示{}i get Object时的预期结果。
注意:对于数组[],我得到的对象没有问题。
{}
被解释为(空)代码块,而不是对象文本。它没有返回值,因此默认为undefined
如果输入,您将得到相同的结果代码>
要获得一个实际的对象,您需要确保{
被解释为表达式的一部分,而不是语句的开头,例如使用({})
如果您使用eval({})
Javascript将把{}视为一个空块,而不是对象。我(和许多开发人员)非常不鼓励使用eval()
您可以使用eval((“+提示(“请输入值”)+”);
区别在于:
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"
尝试使用typeof Primitive[i]
instead如果使用eval({})
Javascript会将{}视为一个空块,而不是一个对象。我(和许多开发人员)强烈反对使用eval()
请不要使用eval
,尤其是当你正在eval
ing的东西不需要eval
ed时。Me:entries0);alert(“no”);//
mm,这是真的。你能给我一个区别的例子吗。@打字速度快的人非常感谢你的帮助