标签:
晚上下班的时候,我们又开始讨论无聊的问题。一个同事提出如下怪异的场景,据说是一道面试题:
var o = {
1:'a'
,2:'b'
,length:2
,push:Array.prototype.push
};
o.push('c');Q:o现在内部的值是什么样子?
我的第一反应是排斥,为什么要研究不合理情况下【解释引擎】的行为?但是这种推论有时候又很吸引人,于是我回来的时候仔细思考了下,发现其实很简单。
对于push这个方法,我条件反射地想到的就是栈,【数据结构的经典栈】中压栈和弹栈操作依据的都是栈顶指针,栈顶指针始终指向栈顶,意味着它会因为压弹栈而自动增减。在javascript中的数组中这个指针就是length。所以在上面的代码中,o.push(‘c‘)就是o.2 = ‘c‘(当然o.2不能直接访问,这只是伪代码),所以代码执行完o中数据如下:
{
1:'a'
,2:'c'
,length:3 //push操作=>length+1
,push:Array.prototype.push
}//1.length不存在,引擎置为0
var o = {
'1':'a'
,'2':'b'
,push:Array.prototype.push
};
o.push('c');//c {0:'c',1:'a',2:'b',...}
//2.length为负值,这是个有趣的问题,涉及到原码反码和补码【1】
var o = {
'1':'a'
,'2':'b'
,length:-1
,push:Array.prototype.push
};
o.push('c');//c {1:'a',2:'b',4294967295:'c',length:4294967296,...}
//3.length为字符或对象
var o = {
1:'a'
,2:'b'
,length:'A'
,push:Array.prototype.push
};
o.push('c');//c {0:'c',1:'a',2:'b',length:1,...}我还以为js解释器会把A转换成ASCII码来给length赋值呢,终于看到了javascript的自由还是有节操的标签:
原文地址:http://blog.csdn.net/longjuesi/article/details/44970773