阐述了用JavaScript定义和输出螺旋矩阵的方法。分享给大家参考,如下:
昨晚不是故意要看到这样的算法,然后就想着用js来实现。昨晚潦草写完,觉得代码又丑又臭,所以今晚花了点时间重构,感觉很优雅。
什么是螺旋矩阵
螺旋矩阵指的是一个螺旋矩阵,它的数字从第一行开始向右、向下、向左、向上等变大。
如图所示:
达到效果
实现代码
(function(){ var map=(function(){ function map(n){ this . map=[],this.row=0,this.col=-1,this.dir=0,this.n=n//为(var i=0)创建二维数组;I此. n;I){ this . map . push([]);}//定义移动顺序为右、下、左、上var顺序=[this。对,这个。底部,这个。左边,这个。up];I=0;如果确实{//可以移动,请更新数字,否则请更改方向顺序[this.dir% 4]。打电话(这个)?i : this.dir//赋值this . map[this . row][this . col]=I;} while(I n * n);} map . prototype={ print : function(){ for(var I=0;I此. n;I) {console.log(这个。地图【我】。join(“”)},//move left : function(){ return this。移动(这个。划,这个。col-1)在这个方向上;},right : function(){ return this . move(this . row,this . col 1);},up : function(){ return this . move(this . row-1,this . col);},bottom : function(){ return this . move(this . row 1,this . col);},//如果坐标在范围内,而目标没有值,则更新坐标move:function (row,col) {return (0=rowrowthis。n) (0=colcolthis。n)!this . map[row][col](this . row=row,this.col=col,true);}, };返回地图;})();新地图(6)。print();})();更多对JavaScript相关内容感兴趣的读者可以查看本网站专题:《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript数组操作技巧总结》、《JavaScript事件相关操作与技巧大全》、《JavaScript操作DOM技巧总结》、《JavaScript字符与字符串操作技巧总结》、0103010。
希望本文对JavaScript编程有所帮助。