- toString() , valueOf() 與 Java 、 ActionScript3 基本原理相似。
(function(){
Object.prototype.valueOf = function(){
return 6;
}
Object.prototype.toString = function(){
return 10;
}
var val2 = {
x:2 ,
y:3
};
alert(val2); //10
alert(val2 * 2 );//12 遇到算數運算會隱含調用Object的valueOf()
var val3 = {
x:5 ,
y:6 ,
toString:function( ){
return '龍虎門';
}
};
alert(val3); //龍虎門 調用toString()
})();
Array Native forEach
var data = [3,5,6,9,7,8,4,3,2,1];
var str = '';
//array native forEach
data.forEach(function(e){
str += e + ',';
});
//print 3,5,6,9,7,8,4,3,2,1
console.log(str.substring(0,str.length-1));
Array Native Sort
var data = [3,5,6,9,7,8,4,3,2,1];
var str = '';
data.sort();
data.forEach(function(e){
str += e + ',';
});
//1,2,3,3,4,5,6,7,8,9
console.log(str.substring(0,str.length-1));
Customer Compare Funciton
var data = [3,5,6,9,7,8,4,3,2,1];
var str = '';
function compare(a,b){
return b - a;
}
data.sort(compare);
data.forEach(function(e){
str += e + ',';
});
//9,8,7,6,5,4,3,3,2,1
console.log(str.substring(0,str.length-1));