首頁  >  問答  >  主體

如何在函數呼叫之前改變一個物件?這樣真的可行嗎?

<p>我有一個很奇怪的js問題。我有一個Vue組件(但我認為Vue在這裡不重要)。它有一個名為<code>current_query</code>的資料屬性。在回應事件的方法中,我想修改該屬性。在這裡使用Lodash。有一個非常奇怪的行為。假設<code>this.current_query</code>最初等於<code>{ test: 500 }</code>。假設<code>'field'</code>參數為<code>'test'</code>。透過從<code>current_query</code>中「取消設定」它,實際上我將清空current_query本身。很好。問題是,只有在使用unset時,如果我在呼叫unset之前記錄current_query,我將得到一個空物件。這怎麼可能? </p> <pre class="brush:php;toolbar:false;">on_applied_option_click(field){ console.log(this.current_query); // 給出{ test: 500 }(OK) }, // 點擊結束 on_applied_option_click(field){ console.log(this.current_query); // 只有在使用_.unset時,才會給予空物件(??) _.unset(this.current_query, field); console.log(this.current_query); // 也會給予空物件(OK) }, // 點選結束</pre> <p>我發現如果我使用<code>_.omit</code>,一切都很好:</p> <pre class="brush:php;toolbar:false;">on_applied_option_click(field){ console.log(this.current_query); // 給出{ test: 500 }(OK) this.current_query = _.omit(this.current_query, field); console.log(this.current_query); // 給予空對象,此時是可以的 }, // 點選結束</pre> <p>為什麼?我唯一能說的是,_.unset會改變對象,而_.omit會建立新對象。但是,我認為在呼叫之前,_.unset改變物件是不可能的(???)。從未見過這樣的事情。有人對這種奇怪的行為有什麼好的解釋嗎? </p>
P粉539055526P粉539055526416 天前396

全部回覆(1)我來回復

  • P粉301523298

    P粉3015232982023-08-31 10:43:44

    不要使用console.log(this.current_query),嘗試使用console.log(JSON.stringify(this.current_query))。這樣可以可靠地記錄this.current_query在記錄時的狀態,而不是可能之後的某個狀態。

    這樣應該可以解決混淆問題。

    回覆
    0
  • 取消回覆