iT邦幫忙

0

javascript的變數會相互影響?

  • 分享至 

  • twitterImage

大家好,我是剛開始學習javascript的菜鳥,因為之前是使用C#寫所以從typescript下手,風格比較相近,最近練習資料結構的linkedlist,但在沒有指標的狀況下新增node的部分觀念一直卡關,所以參考網路上的範例看完我更不懂了,以下是新增node的程式碼已轉換成javascript

//node
var LinkedListItem = /** @class */ (function () {
    function LinkedListItem(val) {
        this.value = val;
        this.next = null;
    }
    return LinkedListItem;
}());
//linkedlist
var LinkedList = /** @class */ (function () {
    function LinkedList(item) {
        this.head = item;
    }
// Adds the element at the end of the linked list
    LinkedList.prototype.append = function (val) {
        var currentItem = this.head;
        var newItem = new LinkedListItem(val);
        if (!this.head) {
            this.head = newItem;
        }
        else {
            while (true) {
                if (currentItem.next) {
                    currentItem = currentItem.next;
                }
                else {
                    currentItem.next = newItem;
                    break;
                }
            }
        }
    };

我的理解是this.head是屬於全域變數,currentItem是區域變數,雖然一開始this.head把值傳給currentItem,但這兩個應該還是各自獨立的變數,然而跑出來的結果是currentItem的改變會影響到this.head的值,這是為什麼呢?請前輩們指導一下謝謝

tacodrem iT邦新手 5 級 ‧ 2018-06-19 10:34:24 檢舉
別用var, 改用let看看呢?
小魚 iT邦大師 1 級 ‧ 2018-06-19 12:36:13 檢舉
這種寫法的確很像C#,
但是你在原始部落殺人是英雄,
不代表你來到了民主時代殺人不會變成死刑犯...
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
wingkawa
iT邦新手 3 級 ‧ 2018-06-19 10:25:00
最佳解答

應該是因為 javascript 的 Object 都是 Call by reference
可以參考這篇:https://pjchender.blogspot.com/2016/03/javascriptby-referenceby-value.html

這是 javascript比較奇怪(?)的地方,但也不是不合理的bug,這是它的規則之一~

ms0447905 iT邦新手 5 級 ‧ 2018-06-19 10:38:51 檢舉

感謝前輩的回答,我卡了快一星期了,謝謝

froce iT邦大師 1 級 ‧ 2018-06-19 11:39:53 檢舉

這幾乎是靜態語言寫慣的人,轉換到動態語言一定會踩到的雷。
python也是一樣的設計。

我要發表回答

立即登入回答