[译]在Javascript中制造二维数列
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单
源地址在此:
https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b
Javascript中并不存在直接制造二维数列的方法,所以我们其实只是制作一个包含着数列的数列而已
例子:以下的Javascript代码制造一个3x3的二维数列
for (i=0; i [ 3; i++) myArray1[i]=new Array(3) myArray1[0][0] = "1" myArray1[0][1] = "2" myArray1[0][2] = "3" myArray1[1][0] = "4" myArray1[1][1] = "5" myArray1[1][2] = "6" myArray1[2][0] = "7" myArray1[2][1] = "8" myArray1[2][2] = "9" for (var i = 0; i < 3; i++) { for (var j = 0; j [<3; j++) { document.write(myArray1[i][j] + " "); } document.write("[br/]"); }
在例1中,我们亲手在数列中的每个储存位置填充了元素,而在以下的例子中,我们用2个嵌套for循环来达到以上的效果
var myArray1 = new Array(3) for (i=0; i [ 3; i++) myArray1[i]=new Array(3) var start = 1; for (var i = 0; i <3; i++) { for (var j = 0; j [<3; j++) { myArray1[i][j] = start; start = start + 1; } } for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { document.write(myArray1[i][j] + " "); } document.write("[br/]"); }
在两个二维数列中进行加法运算
例子:
第一个3x3的数列必须包含从1到9的数字
第二个3x3的数列必须包含从9到1的数字
在第一个和第二个数列中index相同位置的数目必须进行相加运算,然后将结果存储到第三个3x3的数列中
// Create the first 2 dimensional 3 X 3 array var myArray1 = new Array(3) for (i=0; i < 3; i++) myArray1[i]=new Array(3) var start = 1; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { myArray1[i][j] = start; start = start + 1; } } for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { document.write(myArray1[i][j] + " "); } document.write("<br/>"); } document.write("<br/>"); document.write(" +"); document.write("<br/>"); document.write("<br/>"); // Create the second 2 dimensional 3 X 3 array var myArray2 = new Array(3) for (i = 0; i < 3; i++) myArray2[i] = new Array(3) for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { start = start - 1; myArray2[i][j] = start; } } for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { document.write(myArray2[i][j] + " "); } document.write("<br/>"); } document.write("<br/>"); document.write(" ="); document.write("<br/>"); document.write("<br/>"); // Create the third 2 dimensional 3 X 3 array var myArray3 = new Array(3) for (i = 0; i [ 3; i++) myArray3[i] = new Array(3) for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { myArray3[i][j] = myArray1[i][j] + myArray2[i][j]; } } for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { document.write(myArray3[i][j] + " "); } document.write("<br/>"); } Creating a 2 dimensional 3 X 5 array var myArray1 = new Array(3) for (i=0; i < 3; i++) myArray1[i]=new Array(5) var start = 101; for (var i = 0; i < 3; i++) { for (var j = 0; j < 5; j++) { myArray1[i][j] = start; start = start + 1; } } for (var i = 0; i < 3; i++) { for (var j = 0; j < 5; j++) { document.write(myArray1[i][j] + " "); } document.write("<br/>"); }
小白前端学习之路