簡體   English   中英

為什么js object在被分配前console.log中不為空?

[英]Why is js object not empty in console.log before being assigned?

我遇到了關於 JS 對象的意外行為。 請糾正我做錯了什么。

<?php // BISMILLAHIRRAHMANIRRAHEEM
?>
<!DOCTYPE html>
<head>
    <title>test</title>
    <script>
        var testobj = {};
        var ret = '{"status":true,"Action":"GetContacts","data":{"0":{"company":"abc","faxnumber":"111"},"1":{"company":"def","faxnumber":"222"},"2":{"company":"ghi","faxnumber":"333"}},"message":""}';
        var retobj = JSON.parse(ret);
        function Process() {
            var list = retobj["data"];
            // Label 1
            testobj = {};
            console.log(testobj);
            // Label 2
            testobj = {};
            console.log(testobj); // Not empty!!
            // Label 3
            //testobj = {};
            //console.log(testobj);
            Object.keys(list).forEach(function(key) {
                testobj[key] = {};
                testobj[key]["Name"] = list[key]["company"];
                testobj[key]["Number"] = list[key]["faxnumber"];
            });
            // Label 4
            console.log("After assigned:");
            console.log(testobj);
        }
    </script>
</head>
<body>
    <a href="javascript:Process();">Click</a>
</body>
</html>

我需要將 object 重置為空。 (我在這個網站上閱讀了關於delete帖子)。 在嘗試其他選項時,我正在尋找關於為什么testobj沒有在控制台 output 中記錄為空的解釋? 控制台輸出testobj填充的數據,預計稍后將在代碼中填充。 如果我注釋掉// Label 2下的兩行代碼,控制台 output 下// Label 1會給出一個填充的testobj 同樣,如果// Label 1, 2, 3注釋,則控制台 output 將前兩個testobj為空,第三個填充有待填充的數據。 不知何故testobj = {};的最新分配正在將 object 分配給即將分配的數據。 它發生在Process(); 當 object 至少最初應該是空的時也是如此。

請指出正確的方向。 我已經在 Firefox v75.0 和 Chrome v81.0.4044.129 上對此進行了測試

閱讀這篇文章的答案,控制台將前兩個對象顯示為空直到展開是有道理的:

Object {  } // <--- empty

Object {  } // <--- not empty

After assigned:
Object { 0: {…}, 1: {…}, 2: {…} }

...此時它應該顯示 object 的當前 state。 但是,無論您在控制台中以哪種順序展開 object 節點,最后一個testobj = {}; forEach循環之前是顯示 object 的當前/更新值的循環。 這是為什么? 取消注釋所有三個標簽給出:

Object {  } // <--- empty

Object {  } // <--- empty

Object {  } // <--- not empty

After assigned:
Object { 0: {…}, 1: {…}, 2: {…} }

此外,在 Chrome 調試器中顯示每個 object:

下面的值是剛才評估的

更新: console.log(JSON.parse(JSON.stringify(testobj))); 在所有三個 label 案例中顯示預期的 output(所有對象在分配之前為空)。 我仍然覺得奇怪的是控制台顯示當前/(實時?) object 值僅適用於最后一個testobj = {}; 在分配值之前。

您的代碼在 label 1 和 2 下記錄了兩個空對象。

在 label 3 下,您根據列表 ZA8CFDE6331BD59EB2AC96F89 將屬性從 label 2 分配給 object 2。

Next, when you expand the object from label 2, the browser re-interprets what was logged (it doesn't keep a copy), and looks at the current state of the object, which you modified under label 3. That is what you正在看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM