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

时间:2015-01-26 06:01:18

标签: javascript arrays

请检查小提琴 - 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)它在第一个日志条目中记录为原始值,然后将日志类型记录为对象。有些事情是不对的,或者是用词不当。

2)仅记录"此"(第一个日志语句)提供了更多详细信息,但是当在第二个语句中登录时,它只打印该值。为什么呢?

4 个答案:

答案 0 :(得分:2)

当您使用callapply$.each在幕后做什么)并传递基元时,JS隐含地"框"它成为相应的对象类型:



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

foo.apply(123)




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

  
      
  1. < ...>如果Type(thisArg)不是Object,则将ThisBinding设置为ToObject(thisArg)。
  2.   

答案 1 :(得分:1)

那些不是原始的。比较:

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

第一个值是基元;第二个是包装基元的对象(即盒装版本)。

至于为什么会发生这种情况,$.each是根据Function.prototype.call实现的,其文档中有这一点(MDN):

  

为{em> fun 调用提供的this值。请注意,这可能不是该方法看到的实际值:如果该方法是非严格模式代码中的函数,则nullundefined将替换为全局对象,并且原始值将加框

(强调我的)

答案 2 :(得分:0)

如果使用+运算符,js会将整个事物转换为字符串。

您可能想要使用的是:

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

用逗号。

答案 3 :(得分:0)

这是更新的代码。 你可能期望这个结果比你的结果好吗?

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]);
}
相关问题