数组篇
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
})