javascript那些事

数组篇

Object.keys方法返回数组的所有键名。

对象的键名一律为字符串,所以,数组的键名其实也是字符串。之所以可以用数值读取,是因为非字符串的键名会被转为字符串。

var arr = [1,2,3]
arr['0'] //1
arr[0]    //1

对象有两种读取成员的方法:点结构(object.key)和方括号结构(object[key])。但是,对于数值的键名,不能使用点结构。

使用delete命令删除一个数组成员,会形成空位,并且不会影响length属性。

var a = [1,2,3,4]
delete a[1]
a[1]  //undefiend
a.length  //4

数组的某个位置是空位,与某个位置是undefined,是不一样的。如果是空位,使用数组的forEach方法、for...in结构、以及Object.keys方法进行遍历,空位都会被跳过。

var a = [,,,]
a.forEach((x) =>{
    console.log(a+'test')
})
for(var i in a) {
    console.log(i+'test2')
}
Object.keys(a)

如果某个位置是undefined,遍历的时候就不会被跳过。

var b = [undefined,undefined,undefined]
b.forEach((x) =>{
    console.log(x)
})     //undefined,undefined,undefined
for(var i in b) {
    console.log(i)
}      //0,1,2
Object.keys(b)  //['0','1','2']

类数组这种length属性不是动态值,不会随着成员的变化而变化。

var c = {
    1:'a',
    2:'b',
    length:2
}
c[0] //undefined
c[1] //'a'
c.length //2
c.push('d') //c.push not a function


var c = {
    length:0
}
c[3] = 'd'
c.length   //0

典型的“类似数组的对象”是函数的arguments对象,以及大多数 DOM 元素集,还有字符串。

function test() {
    return arguments
}
var a = test('a','b')

a.length;//2
a[1]//'b'
a instanceof Array//false

var b = document.getElementsByTagName('h3')
b.length //'b'
b instanceof Array //false

'abc'[1] //'b'
'abc'.length //3
'abc' instanceof Array //false

数组的slice方法可以将“类似数组的对象”变成真正的数组。

var arr = Array.prototype.slice.call(a)

除了转为真正的数组,“类似数组的对象”还有一个办法可以使用数组的方法,就是通过call()把数组的方法放到对象上面。

function arr() {return arguments}
var a = arr('a','b','c')

function print(value, index) {
    console.log(index + ":" + value)
}
Array.prototype.forEach.call(a, print)   //0:a 1:b 2:c

a代表一个类似数组的对象,本来是不可以使用数组的forEach()方法的,但是通过call(),可以把forEach()嫁接到a上面调用。

function log() {
    Array.prototype.forEach.call(arguments, (index, value) => {
        console.log(indx + '.' + value)
    })
}
function lig2() {
    for (var i = 0; i < arguments.length; i++) {
        console.log(i + '.' + arguments[i])
    }
}

字符串也是类似数组的对象,所以也可以用Array.prototype.forEach.call遍历。

Array.prototype.forEach.call('abc', (index) => {
    console.log(index)
})//a b c

这种方法比直接使用数组原生的forEach要慢,所以最好还是先将“类似数组的对象”转为真正的数组,然后再直接调用数组的forEach方法。

var arr = Array.prototype.slice.call('abc')
arr.forEach((index) =>{
    console.log(index)   //a b c
})




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值