Javascript中如何引用指针2013-10-14 本站 本文介绍Javascript中引用指针的方法。请尝试完成下列完形填空:
/* 创建一个队列,头为head0,尾为tail0 */function IntList(head0, tail0){this.head = head0 || 0;this.tail = tail0 || null;}/* 返回一个IntList包含数组中的所有数 */IntList.list = function(__args){var sentinel = new IntList(),len = __args.length,p;p = sentinel;for(var i = 0; i < len; i++){p.tail = new IntList(__args[i]);p = p.tail;}return sentinel.tail;};/* 返回该对象的字符串表示 */IntList.prototype.toString = function(){var temp = "";temp += "[";for(var L = this; L !== null; L = L.tail){temp = temp + " " + L.head;}temp += " ]";return temp;};/** 返回一个IntList,包含IntList A和IntList B, *其中B的元素在A的后面。不能使用new关键字。 */function dcatenate(A, B){/* 完成功能 */}/** 返回一个新的IntList,其长度为len, *以#start元素为开头(其中#0是第一个元素), *不能改变L。 */function sublist(L, start, len){/* 完成功能 */}这是一个用Javascript写的链表题。由于链表拥有较为复杂的引用操作,正好可以用来考察下对Javascript的引用的理解。附带简单的测试用例:
/* 测试dcatenate和sublist函数是否正确 */function test(){var A = IntList.list([4,6,7,3,8]),B = IntList.list([3,2,5,9]);dcatenate(A, B);if(A.toString() === "[ 4 6 7 3 8 3 2 5 9 ]"){alert("dcatenate函数正确。");}else{alert("dcatenate函数错误。");}var L = IntList.list([3,4,5,2,6,8,1,9]),result = sublist(L, 3, 3);if(result.toString() === "[ 2 6 8 ]"){alert("sublist函数正确。");}else{alert("sublist函数正确。");}}