JavaScript学習ノート5組

1788 ワード

//  ,    pop,push         ,   slice, reverse,sort           
var arr = new Array(1,1,1,2,3,1);
arr.sort();alert(arr);//   sort                ,                 
arr.sort(function(a, b){return a - b;});alert(arr);//    ,            
arr.sort(function(a, b){return b - a;});alert(arr);//    ,            

arr.length = 3;alert(arr);//         ,    length           

var array = ["one", "two", "three", "four"];//        
var array2 = ["yet", "another", "array"];
var newArr = arr.concat(array,array2);//  

alert(newArr.slice(2,4));//    newArr      2        4      
var ssArr = newArr.slice(2);
newArr.splice(2,4);alert(newArr);//        4   
newArr.splice(2,0,"aa","bb");alert(newArr);//       0   ,        
var str = array.join("|");//     |        
alert(str);

//    ,               
//       
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};
array.remove(2);
alert(array);

//        ,            
//     JavaScript     Array         
Array.remove = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
}
Array.remove(array,0,2);//  0, 1, 2    
//   :        ,             ,               
//                       “  ”,              bug    。