簡體   English   中英

Javascript 關聯數組中不可接受的值

[英]Unacceptable value in associative array in Javascript

我在 JavaScript 中的二維數組中的關聯數組中設置了值。 我使用了以下源代碼:

 var properties = { "isBold": false, "isItalic": false, "isUnderline": false }; // Creation of 2D array, 6x6 var listOfProperties = new Array(6); for (var i = 0; i < listOfProperties.length; i++) { listOfProperties[i] = new Array(6); } // Population of listOfProperties with properties for (var row = 0; row < listOfProperties.length; row++) { for (var col = 0; col < listOfProperties.length; col++) { listOfProperties[row][col] = properties; } } var property = listOfProperties[2][2]; property.isBold = true; // I would like to populate property isBold console.log("property > " + property.isBold); var property = listOfProperties[0][0]; console.log("property > " + property.isBold);

我創建了用屬性填充的二維數組(關聯數組,所有值都是假的)。 然后我為 *listOfProperties[2][2]** 為isBold設置了true

但是為什么listOfProperties [0][0]中的isBold包含true而不是false

您需要填充對象副本的二維數組,而不是引用:

 var properties = { "isBold": false, "isItalic": false, "isUnderline": false }; // Creation of 2D array, 6x6 var listOfProperties = new Array(6); for (var i = 0; i < listOfProperties.length; i++) { listOfProperties[i] = new Array(6); } // Population of listOfProperties with properties for (var row = 0; row < listOfProperties.length; row++) { for (var col = 0; col < listOfProperties.length; col++) { listOfProperties[row][col] = Object.assign({}, properties); } } var property = listOfProperties[1][1]; property.isBold = true; // I would like to populate property isBold console.log("property > " + property.isBold); var property = listOfProperties[0][0]; console.log("property > " + property.isBold);

有關更多詳細信息,請查看

暫無
暫無

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

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