javaScript基础(13):(数组和类数组)

96 阅读1分钟

打好基础,查漏补缺

基础是重中之重

数组的定义方式

var arr = []
var arr1 = new Array()  
使用构造函数定义数组时,如果传参只有一位将理解成构造数组的长度 new Array(2)

数组的常用方法

能改变原数组
push、pop、shift、unshift、sort、reverse,splice

不影响原数组
concat、slice、join、toString、split
// push 在数组的最后一位添加数据
Array.prototype.push=function(){
    for(var i = 0; i < arguments.length; i++){
        this[arguments.length] = arguments[i]
    }
}
Array.prototype.unshift=function(){
    argument.concat(this)
  return  this.length
}

// sort 排序 默认按Unicode码排序
// sort 回调函数中必须有两个参数
//      如果返回值为负数,前面的数在前面
//      如果返回值为正数,后面的数在前面
arr.sort(function(a,b){
    return a-b // 升序
})

//使一个有序数组乱序
arr.sort(function(a,b){
    return Math.random() - 0.5
})

类数组

1、属性要为索引(数字), 2、必须要length属性 3、最好加上push

var obj ={
		'0':'a',
		'2':'b',
		'3':'c',
		"length":3,
		"push":Array.prototype.push,
		"splice":Array.prototype.splice
}d
obj.push('d') // // obj ={
            //		'0':'a',
            //		'2':'b',
            //		'3':'d',
            //		"length":4,
            //		"push":Array.prototype.push,
            //		"splice":Array.prototype.splice
        //      }