こんにちは,
JavaScriptの背景知識
JavaScriptは
(広義の)
ECMAScriptは比較的
さて,
よって,
JavaScriptのオブジェクトと型
JavaScriptのデータ型は大きく分けて
JavaScriptのprototype
JavaScriptはprototypeベースの言語です。null,
例えば下記のようにString.
String.
if (!String.prototype.trim) {
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g, '');
}
}
' string \u00a0 \t \v \f '.trim() // -> 'string'
なお,
こういったprototypeの拡張は便利ですが,
Array.
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(func, that) {
for (var i = 0, len = this.length; i < len; i++) {
if (i in this) {
func.call(that, this[i], i, this);
}
}
};
}
var a = [1,2];
a.forEach(function(v,i,a){
alert(v);// 1, 2
});
for (var i in a) {
alert(i);// 0, 1, forEach
}
for (var i in a) {
if (a.hasOwnProperty(i)) {
alert(i);// 0, 1
}
}
IEで上記のコードを実行すると途中でforEachがアラートされます。hasOwnPropertyというメソッドで自分自身がもつプロパティかどうかチェックすることで回避することはできますが,
Object.
なお,