JS中引用对象的问题

问题描述

新人,学习删除select列表中option的时候遇到了一个变量引用的问题,如下:
1.用option[index] = null ,可以达到删除目的;
2.把option[index]赋值给某个变量,再把变量设置为null,无效,例:

var a = option[index];
a = null;

经思考后,已经明白了a实际是引用了option[index]的地址,后面设置a = null,只是改变了a的引用地址,option[index]实际没有变化。但是,后面的问题我想不通了,代码贴在下面。

代码

<form action="" name="theForm">
    <select name="theDay">
        <option value="1">1</option>
    </select>
</form>
<script>
    var option = document.theForm.theDay.options[0];
    document.theForm.theDay.options[0] = null;
    console.log(document.theForm.theDay.options[0]); //输出 undefined 
    console.log(option); // 输出 <option value="1">1</option>
</script>

而我以为的输出会是

console.log(document.theForm.theDay.options[0]); //输出 null 
console.log(option); // 输出 null

想了很久没想明白,希望大神指点

阅读 2k
2 个回答

用option[index] = null ,可以达到删除目的是因为浏览器的垃圾回收机制造成的,他只是删除了内存中被引用的对象。

var a = {};
a = null

这里回收与删除的只是空对象,但是变量a还是存在的。

如果option是一个数组,你就会发现option[index]变成了null,也就是下面你以为的输出。但是这里你的option并不是一个数组,而是类数组对象HTMLOptionsCollection(option集合,继承于HTMLCollection)

当你使用option接收theForm.theDay.options[0]时,option就引用了这个option对象,当你置空theForm.theDay.options[0]时,类数组对象的长度就变味0了,当你在访问的时候就变成了undefined,而不是你以为的null。同时,因为还有一个option变量指向该option对象,所以该option对象并没有被回收,当你打印option时还是可以但因出该dom对象。

首先document.theForm.theDay.options[0] = null是改变options[0]内存的指向,但option的指向没有改变,仍指向<option>的实例(instance),所以第二个console打印出<option>的实例。

其次document.theForm.theDay.options[0] = null会把这唯一的<option>从文档中删除,所以再执行document.theForm.theDay.options[0]去查询的时候会找不到,返回undefined。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题