回答編集履歴

2

解説

2019/05/08 11:08

投稿

yambejp
yambejp

スコア114839

test CHANGED
@@ -77,3 +77,47 @@
77
77
 
78
78
 
79
79
  ※コメントつけておきました
80
+
81
+
82
+
83
+ # 解説
84
+
85
+ ```javascript
86
+
87
+ l=(l.match(/\d+/))?reg[0]:"0";
88
+
89
+ ```javascript
90
+
91
+ 上記分解すると
92
+
93
+ ```javascript
94
+
95
+ reg=l.match(/\d+/)
96
+
97
+ ```
98
+
99
+
100
+
101
+ \dは0-9の数字それに+がついてるので1文字以上の数字
102
+
103
+ それをスラッシュで挟んでmatchにあたえると
104
+
105
+ 変数lの文字列の中にある数字を拾い、結果をregという変数に配列として返します。
106
+
107
+
108
+
109
+ ```javascript
110
+
111
+ l=条件?reg[0]:"0";
112
+
113
+ ```
114
+
115
+ 条件の中でregに数値がはいっていればその数値であるreg[0]をlに代入します
116
+
117
+ そうでないとき(つまりlに数値が含まれないとき)にはlには"0"を代入します
118
+
119
+ これを三項演算子といいます
120
+
121
+
122
+
123
+ 結果としてlの中から数値だけを取り出してlに入れ直しています

1

調整

2019/05/08 11:07

投稿

yambejp
yambejp

スコア114839

test CHANGED
@@ -18,7 +18,11 @@
18
18
 
19
19
  var time=5;
20
20
 
21
+ var Mario;
22
+
21
23
  window.addEventListener('DOMContentLoaded', function(e){
24
+
25
+ Mario=document.querySelector('#mario');
22
26
 
23
27
  MarioMove();
24
28
 
@@ -34,11 +38,19 @@
34
38
 
35
39
  function step() {
36
40
 
37
- var Mario=document.querySelector('#mario');
41
+ var l=Mario.style.marginLeft;
38
42
 
39
- Mario.style.marginLeft = (parseInt((Mario.style.marginLeft.match(/\d+/)||["0"])[0])+50)+"px";
43
+ l=(reg=l.match(/\d+/))?reg[0]:"0"; //数値を含めばその数、なければ0
40
44
 
45
+ l=parseInt(l); //文字列を数値化
46
+
47
+ l+=50; //数値に50を加算
48
+
49
+ l+="px"; //単位を付加
50
+
41
- console.log(Mario.style.marginLeft);
51
+ console.log(l);
52
+
53
+ Mario.style.marginLeft = l; //値を代入
42
54
 
43
55
  time--;
44
56
 
@@ -61,3 +73,7 @@
61
73
  <img id="mario" src="https://placehold.jp/ff0000/00ffff/100x100.png?text=mario">
62
74
 
63
75
  ```
76
+
77
+
78
+
79
+ ※コメントつけておきました