(http://eloquentjavascript.net/07_elife.html)एक ग्रिड की स्थापना। वाक्पटु js अध्याय 7
इम एक कठिन समय समझ में क्या ग्रिड तरीकों हम .Get जोड़ा गया है और यहां तक कि do.Firstly .Set होने की सुविधा देता है एक उदाहरण के मामले के माध्यम से जाना। var grid = new Grid(5,5)
; अब स्थान 25
तत्वों की एक सरणी है। और निश्चित रूप से width
और height
are
5.
अब सवाल यह है कि "पाने" की विधि क्या है।
अब हम कहा console.log(grid.get(new Vector(1, 1)));.
तो x
1
हो जाता है, y
नई वस्तु हम बनाया में 1
हो जाता है। बेशक हमें ग्रिड करने की ज़रूरत है। इस प्रकार हम this.space[1+ 1 * 5]
पर वापस आते हैं यानी स्पेस सरणी में 6 वें स्थान पर 25
तत्व लंबे हैं। तो यह प्रिंट अपरिभाषित क्यों करता है? क्या ऐसा इसलिए है क्योंकि अंतरिक्ष सरणी में कुछ भी नहीं है?
TLDR
कैसे .get
और .set
प्रोटोटाइप यहाँ काम करते हैं (वे क्या करते हैं)? हम return this.space[vector.x + this.width*vector.y];
क्यों सेट करते हैं, क्या vector.x+this.width*vector.y
पर कुछ संख्यात्मक महत्व है?
function Vector(x,y){
this.x = x;
this.y = y;
}
Vector.prototype.plus = function(other){
return new Vector(this.x + other.x, this.y + other.y);
}
var grid = ["top left", "top middle", "top right",
"bottom left", "bottom middle", "bottom right"];
function Grid (width,height){
this.space = new Array(width * height);
this.width = width;
this.height = height;
}
Grid.prototype.isInside = function(vector){
return vector.x >=0 && vector.x<this.width && vector.y>=0 && vector.y<this.height;
}
Grid.prototype.get = function(vector){
return this.space[vector.x + this.width*vector.y];
// 5 + 5 * 1;
}
Grid.prototype.set = function(vector,value){
this.space[vector.x + this.width *vector.y] = value;
}
var grid = new Grid(5, 5);
console.log(grid.get(new Vector(1, 1)));
// → undefined
grid.set(new Vector(1, 1), "X");
console.log(grid.get(new Vector(1, 1)));
// → X
हम्म ... मुझे लगता है कि मैं समझता हूं लेकिन मुझे इसके बारे में और अधिक सोचने की आवश्यकता हो सकती है –
तो vector.x + this.width * vector.y वास्तव में क्या प्रतिनिधित्व करता है? क्या वह जगह है जहां हम कुछ लगाने जा रहे हैं? –
मैं जल्द ही कुछ और विवरण जोड़ूंगा कि पूरी वेक्टर चीज कैसे काम करती है ... –