简体   繁体   English

Javascript-一个原始值的typeof是一个对象?

[英]Javascript - typeof a primitive value is an object?

Please check the fiddle - http://jsfiddle.net/n8emgLw9/ 请检查小提琴-http: //jsfiddle.net/n8emgLw9/

var a = [3, 6, 1, "str", 8];
$.each(a, function (i, e, x) {
console.log(this);
console.log(this + " is of type " + typeof this);
});

1) It logs as a primitive value in the first log entry, and then typeof logs as an object. 1)它在第一个日志条目中记录为原始值,然后将typeof日志记录为对象。 Something is not right or it is a misnomer. 某些事情不正确,或者是错误的称呼。

2) logging only "this"(first log statement) gives more details, but when logged in the second statement, it just prints the value. 2)仅记录“ this”(第一条日志语句)提供了更多详细信息,但是在第二条语句中登录时,它仅显示该值。 Why? 为什么?

When you use call or apply (what $.each does behind the scenes) and pass a primitive, JS implicitly "boxes" it into a corresponding object type: 当您使用callapply$.each在后台执行的操作)并传递原语时,JS会将其隐式“装箱”到相应的对象类型中:

 function foo() { document.write(typeof this); document.write(Object.prototype.toString.call(this)); } foo.apply(123) 

Reference: http://ecma-international.org/ecma-262/5.1/#sec-10.4.3 参考: http//ecma-international.org/ecma-262/5.1/#sec-10.4.3

  1. <...> if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg). <...>如果Type(thisArg)不是Object,则将ThisBinding设置为ToObject(thisArg)。

Those are not primitives. 那些不是原始的。 Compare: 相比:

console.log("foo", new String("foo"));
console.log(1,     new Number(1)    );
console.log(true,  new Boolean(true));

The first values are primitives; 第一个值是基元; the second ones are objects that wrap primitives (ie boxed versions). 第二个是包装原语的对象(即盒装版本)。

As to why it happens, $.each is implemented in terms of Function.prototype.call , which has this bit in its documentation ( MDN ): 至于为什么发生, $.each是根据Function.prototype.call ,该Function.prototype.call在其文档( MDN )中具有以下$.each

The value of this provided for the call to fun . this规定的呼叫乐趣 Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed . 请注意,这可能不是该方法看到的实际值:如果该方法是非严格模式代码中的函数,则nullundefined将被全局对象替换, 原始值将被装箱

(Emphasis mine) (强调我的)

If you use + operator, js casts the whole thing to string. 如果使用+运算符,则js将整个内容转换为字符串。

What you probably want to use is: 您可能要使用的是:

console.log(this, " is of type " + typeof this);

with the comma. 用逗号。

Here is updated code. 这是更新的代码。 You may have expected this result than yours? 您可能比您预期的结果更好?

http://jsfiddle.net/n8emgLw9/1/ http://jsfiddle.net/n8emgLw9/1/

var a = [3, 6, 1, "str", 8];

for (var e in a){
    console.log(a[e]);
    console.log(a[e] + " is of type " + typeof a[e]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM