简体   繁体   中英

TypeError when swapping object properties with destructuring assignment

I am trying to swap two object values in JavaScript using the [] = [] method, but my below code fails with an error saying "message": "Uncaught TypeError: Cannot set property '9' of undefined",

 let dataObj={"reg_price":2, "reg_price_alt":5, "ex":9} console.log("before: ", dataObj) [dataObj.reg_price, dataObj.ex] = [4, 5]; console.log("after: ", dataObj)

Is there some syntax I'm missing? I don't understand why this simple code does not work.

The syntax is fine. Add a semicolon to prevent the automatic semicolon insertion from thinking you want to do console.log(...)[...] instead of array destructuring:

 let dataObj = {"reg_price":2, "reg_price_alt":5, "ex":9} console.log("before: ", dataObj); // <-- semicolon [dataObj.reg_price, dataObj.ex] = [4, 5] console.log("after: ", dataObj)

I'd take this a step further and add semicolons after every line. Caveat emptor otherwise. Example of swapping values:

 const o = {a: 0, b: 1}; console.log(o); [oa, ob] = [ob, oa]; console.log(o);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM