今天刷力扣题160.链表相交其中用到了解构赋值,我看了好多遍,真的好多遍,不下20遍,明明跟答案一样啊,就是通过不了,最后发现,解构赋值那里的两句末尾必须加分号!
大家都知道,JS语法太松散了,不写分号大部分时候都没问题,就目前我发现的,要使用解构赋值语句,就必须在末尾加分号,否则就通过不了,我先把通过代码粘贴过来,再说哪里要加分号大家就懂了:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getListLen = function(head) {
let len = 0, cur = head;
while(cur) {
len++;
cur = cur.next;
}
return len;
}
var getIntersectionNode = function(headA, headB) {
let lenA = getListLen(headA)
let lenB = getListLen(headB)
let curA = headA
let curB = headB
// 如果A的len比B的小,就交换,要保证A是最长的
if(lenA < lenB){
// 运用了解构赋值,最后必须带分号啊!!!!
[curA, curB] = [curB, curA];
[lenA, lenB] = [lenB, lenA];
}
// 两者的长度差
let i = lenA - lenB
while(i -- > 0){
curA = curA.next
}
while(curA && curA !== curB){
curA = curA.next
curB = curB.next
}
return curA
};
其中有这么两句代码:
解构赋值是ES6的新语法,要规范严格很多,所以用解构赋值的时候要注意ES6规范!!!