2017-05-24 13 views
0

我是一個函數,我有一個分配問題。JavaScript對象賦值未按預期工作

它看起來像這樣與故障排除的console.log語句:

function myfunc() 
    { 

    the_node = some_array; //with data.$color = #111111 

    console.log('before: '+the_node.data["$color"]); //returns #111111 
    console.log(the_node); //returns #111111 (at data.$color) 

    the_node.data["$color"] = "#000000" ; //the assignment 

    console.log('after: '+the_node.data["$color"]); //returns #000000 
    console.log(the_node); //returns #111111 (should return #000000) (at data.$color) 

    } 

有趣的是,在控制檯上我得到正確的值返回之前和之後變量「the_node.data $顏色「,表明已經進行了賦值,但尚未在對象'the_node'內賦值。

任何想法爲什麼會發生這種情況?

(下面是該對象the_node「與對象「數據」的內容)什麼the_node實際上包含的行

$$family: "class" 

Config: {$extend: false, overridable: true, type: "multipie", color: "#e6e6e6", alpha: 1, …} 

Edge: {$extend: false, overridable: false, type: "none", color: "#ccb", lineWidth: 1, …} 

Label: {$extend: false, overridable: true, type: "Native", style: " ", size: 10, …} 

Node: {$extend: false, overridable: true, type: "multipie", color: "#e6e6e6", alpha: 1, …} 

_angularWidth: 1 

_depth: 1 

_flag: true 

_treeAngularWidth: 3.1666666666666665 


angleSpan: {begin: 0, end: 2.7762911822421428} 

constructor: function() 

data: Object 
$alpha: "1" 
$color: "#87b13e" 
$dim-quotient: 1 
$label-size: 15 
$span: 2.7762911822421428 
class: "trait" 
color: "#000000" 
trait: "endurance" 

Object Prototype 
+0

您的代碼對我而言按預期工作 - 您可以創建一個可運行的示例 –

+0

我無法重現此問題 - 或者以任何方式查看您的問題可以得到你做的結果。我可以理解得到的結果** **其他方式**與* new *值顯示之前和之後它被設置,並有[重複](https://stackoverflow.com/questions/23429203/weird-behavior -with-objects-console-log)。 – Quentin

+0

是的它很奇怪..沒有意義 – haz

回答

0

目前尚不清楚:

 console.log(the_node); //returns #111111 

無法如果上面的行是正確的:

 console.log('before: '+the_node.data["$color"]); //returns #111111 

是正確的?

嘗試:

console.dir(the_node); 

這將導致the_node的全部內容被顯示包括成員。

另外輸入:

console.log(typeof the_node); 

爲了看它是否是一個對象。注意:當用$前綴任何變量時,如果使用jquery'color'成爲一個具有許多額外功能的對象,那麼您不能簡單地分配給$ color,您應該將其分配給像$ color.value之類的東西,或者永遠是你想要分配的對象的一部分。

+0

the_node.data [「$ color」]是一個字符串,並且該節點是一個對象 – haz

+0

ok,在您的評論中,您將數組分配給'the_node','some_array'實際上是一個數組,或者它是一個對象有一個叫'數據'的成員? – SPlatten

+0

是的,這是正確的 - 它與一個成員的對象稱爲數據' – haz