ITeye博客

javascript 数组方法

seong · 2012-01-06 15:30 · JavaScript · Web前端 · Markdown

Array.pop() : 删除数组的最后一项 Array.push(): 在数组的末尾添加项,例如: colors.push('red', 'blue'); Array.shift(): 删除数组的第一个项 Array.unshift():在数组的起始位置添加项,例如: colors.unshift('red', 'blue');

Array.sort(Function): 给数组排序, 需要一个Function参数, 该方法需要进行比较的2个参数 通过返回值来做排序,例如:


	var num = [40,10,8,2,5];
	num.sort(function (var1, var2) {
		return var2 - var1;
	});

在没有Function参数的时候 它会调用每一个项的toString()方法 然后按照字符串类型进行比较

Array.reverse(): 反转数组

Array.concat(): 复制数组,或者在复制数组的同时再添加项, 例如:


	var colors = ['red', 'blue'];
	
	var copied = colors.concat();
	alert(copied);
	
	var newColors = colors.concat('yellow', ['white', 'black']);
	alert(newColors);


Array.slice(Number, Number): 对已有的数组进行分割 并返回新的一个数组,例如


	var colors = ['red', 'blue', 'yellow', 'white', 'black'];
	
	var newColors = colors.slice(2);	// 'yellow', 'white', 'black'
	alert(newColors);
	
	newColors = colors.slice(1, 4);	// 'blue', 'yellow', 'white'
	alert(newColors);


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。