2011-01-19 55 views
0

我需要一個樣品JS對象字面值,可以通過以下方式獲得:需要示例JavaScript對象字面

hist.undo[0].operation[0].x // would print '2' or whatever 
hist.undo[0].operation[0].y // would print '21' or whatever 
// [...] 
hist.undo[2].operation[0].x // would print '32' or whatever 
hist.undo[2].operation[0].y // would print '12' or whatever 

謝謝!

+0

是這個家庭作業? – 2011-01-19 01:59:22

+0

@Toader Mihai Claudiu - 不,我是JSON新手,無法創建對象。 – Rigil 2011-01-19 02:01:57

+0

這篇文章可能會幫助你更好地理解JavaScript對象http://stackoverflow.com/questions/1704618/what-is-the-difference-between-var-thing-and-function-thing-in-javascript – Lance 2011-01-19 02:08:24

回答

0
<html> 
<head> 
</head> 
<body> 
test 
<script> 
hist = { 
"undo" : [ 
    { 
    "operation": [ {"x":"2","y":"21"}, {"x":"x2","y":"y21"} ] 
    }, 
    { 
    "operation": [ {"x":"99","y":"88"} ] 
    }, 
    { 
    "operation": [ {"x":"32","y":"12"} ] 
    } 
] 
}; 
alert(hist.undo[0].operation[0].x); 
alert(hist.undo[0].operation[0].y); 
alert(hist.undo[2].operation[0].x); 
alert(hist.undo[2].operation[0].y); 
</script> 
</body> 
</html> 
1

working jsfiddle example here

var sample_operation_member = {"x": 100, "y": 250}; 
var sample_undo_member = { "operation" : [sample_operation_member, sample_operation_member,sample_operation_member] }; 

var hist = { 
    "undo": [ 
     sample_undo_member, 
     sample_undo_member, 
     sample_undo_member, 
     sample_undo_member 
    ] 
} 

alert(hist.undo[0].operation[0].x); 

,或者更冗長:

var hist = { 
    undo: [ 
     {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]}, 
     {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]}, 
     {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]}, 
     {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]} 
    ] 
} 

alert(hist.undo[0].operation[0].x); 
0
hist = { "undo" : [ 
     {"operation":[ 
     {"x":2,"y":21}, 
     {"x":3,"y":31} 
     ]}, 
     {"operation":[ 
     {"x":4,"y":41}, 
     {"x":5,"y":51} 
     ]}, 
     {"operation":[ 
     {"x":6,"y":61}, 
     {"x":7,"y":71} 
     ]} 
    ] 
    }