-
slice(start,end)用法:
slice方法用于返回?cái)?shù)組中一個(gè)片段或子數(shù)組,如果只寫一個(gè)參數(shù)返回參數(shù)到數(shù)組結(jié)束部分,如果參數(shù)出現(xiàn)負(fù)數(shù),則從數(shù)組尾部計(jì)數(shù)(-3意思是數(shù)組倒第三個(gè)),如果start大于end返回空數(shù)組,值得注意的一點(diǎn)是slice不會改變原數(shù)組,而是** 返回一個(gè)新的數(shù)組 **。
當(dāng)slice方法沒有參數(shù)時(shí),返回值與原數(shù)組相同。
var a = new Array(1,2,3,4,5);
console.log(a); //[1, 2, 3, 4, 5]
console.log(a.slice(1,2));//2
console.log(a.slice(1,-1));//[2, 3, 4]
console.log(a.slice(3,2));//[]
console.log(a); //[1, 2, 3, 4, 5]
console.log(a.slice());//[1,2,3,4,5]
什么是偽數(shù)組?
無法直接調(diào)用數(shù)組方法或應(yīng)用length屬性,但仍可以使用標(biāo)準(zhǔn)數(shù)組的遍歷方法來遍歷它們。
典型的偽數(shù)組是函數(shù)的參數(shù),還有像調(diào)getElementsByTagName,document.childNodes之類的,它們都返回NodeList對象都屬于偽數(shù)組。將偽數(shù)組轉(zhuǎn)化為標(biāo)準(zhǔn)數(shù)組:
function transform(a,b,c) {
var newArr = Array.prototype.slice.call(argument);
return newArr;
}