回答編集履歴
1
`person1\.length` から `person1\.name\.length` へ修正。`prototype` を使ったサンプルコード追記。
test
CHANGED
@@ -1,8 +1,98 @@
|
|
1
1
|
`"[MyData 田中花子]が大きい。"` が出力される結果に間違いはないと思います。
|
2
2
|
|
3
|
-
h
|
3
|
+
同じと評価したいなら `person1.name.length, person1.equals(), persion1.toString(), person1.valueOf()` を使うコードでしょうか。
|
4
4
|
|
5
|
+
本題ではありませんが、`prototype` を使ったコードにするとメモリを節約できると思います。
|
6
|
+
|
7
|
+
|
8
|
+
|
9
|
+
- [String 値の比較 - JSFiddle](https://jsfiddle.net/4b7xw4zd/2/)
|
10
|
+
|
11
|
+
|
12
|
+
|
13
|
+
```javascript
|
14
|
+
|
15
|
+
'use strict';
|
16
|
+
|
17
|
+
function MyData(name,mail,tel){
|
18
|
+
|
19
|
+
this.name = name;
|
20
|
+
|
21
|
+
this.mail = mail;
|
22
|
+
|
23
|
+
this.tel = tel;
|
24
|
+
|
25
|
+
}
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
MyData.prototype = {
|
30
|
+
|
31
|
+
toString: function toString () {
|
32
|
+
|
33
|
+
return "[MyData " + this.name + "]";
|
34
|
+
|
35
|
+
},
|
36
|
+
|
37
|
+
equals: function equals (that) {
|
38
|
+
|
39
|
+
return this.valueOf().length == that.valueOf().length;
|
40
|
+
|
41
|
+
},
|
42
|
+
|
43
|
+
valueOf: function valueOf () {
|
44
|
+
|
45
|
+
return this.toString();
|
46
|
+
|
47
|
+
},
|
48
|
+
|
49
|
+
compareTo: function compareTo (that) {
|
50
|
+
|
51
|
+
return this.valueOf().length - that.valueOf().length;
|
52
|
+
|
53
|
+
}
|
54
|
+
|
55
|
+
};
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
var person1 = new MyData("山田太郎","taro@yamada.hoge","090-9999-9999");
|
60
|
+
|
61
|
+
var person2 = new MyData("田中花子","hanako@tanaka.hoge","080-8888-8888");
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
console.log(person1.name.length === person2.name.length); // true
|
66
|
+
|
67
|
+
console.log(person1.valueOf().length === person2.valueOf().length); // true
|
68
|
+
|
69
|
+
console.log(person1.toString().length === person2.toString().length); // true
|
70
|
+
|
71
|
+
console.log(person1.equals(person2)); // true
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
if (person1 > person2){
|
76
|
+
|
77
|
+
document.write(person1 + " が大きい。");
|
78
|
+
|
79
|
+
} else if (person1 < person2){
|
80
|
+
|
81
|
+
document.write(person2 + " が大きい。。");
|
82
|
+
|
83
|
+
} else {
|
84
|
+
|
85
|
+
document.write(person1 + "と" + person2 + " は、同じ。");
|
86
|
+
|
87
|
+
}
|
88
|
+
|
89
|
+
```
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
(**更新履歴**)
|
94
|
+
|
5
|
-
|
95
|
+
- 2016/03/20 09:08 `person1.length` から `person1.name.length` へ修正。`prototype` を使ったサンプルコード追記。
|
6
96
|
|
7
97
|
|
8
98
|
|