JavaScriptで配列の計算とか
プログラミングの練習
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
function p(a){ console.log(a); } function createCopyArray(a){ var b = []; for(var k in a){ b[k] = a[k]; } return b; } function reverseArray(a){ var len = a.length; var b = createCopyArray(a); for(var i=0; i<len; i++){ a[i] = b[len-1-i]; } } function calcDiff(a, b){ a = Number(a); b = Number(b); if(a<b){ return b-a; }else{ return a-b; } } function main(){ var a = [0,1,2,3,4,5,6,7,8]; var b = createCopyArray(a); var c = []; var len = a.length; reverseArray(b); for(var i=0; i<len; i++){ c[i] = calcDiff(a[i], b[i]); } p(a); p(b); p(c); } main(); |
1 2 3 |
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ] [ 8, 7, 6, 5, 4, 3, 2, 1, 0 ] [ 8, 6, 4, 2, 0, 2, 4, 6, 8 ] |