标签:
1.添加元素
var nums = [3,4,5];
nums.unshift(1,2);
print(nums); // 1,2,3,4,5
var nums = [1,2,3];
nums.push(4,5);
console.log(nums); //[1, 2, 3, 4, 5]
var nums = [1,2,3,7,8,9];
var newElements = [4,5,6];
nums.splice(3,0,newElements);
print(nums); // 1,2,3,4,5,6,7,8,9
2.删除
var nums = [1,2,3,‘Amy‘,‘Leo‘];
nums.pop();
console.log(nums); //[1,2,3,‘Amy‘]
var nums = [1,2,3,‘Amy‘,‘Leo‘];
nums.shift();
console.log(nums); //[2,3,‘Amy‘,‘Leo‘]
var nums = [1,2,3,‘Amy‘,‘Leo‘,55,3];
nums.splice(1,3);
console.log(nums); //[1, "Leo", 55, 3]
3.截取合并
var itDiv = [‘Mike‘,‘Clayton‘,‘John‘,‘Marry‘,‘Raymon‘];
var dmpDept = itDiv.splice(2,2);
var cisDept = itDiv;
console.log(dmpDept); // [‘John‘,‘Marry‘]
console.log(cisDept); //[‘Mike‘,‘Clayton‘,‘Raymon‘]
var num1 = [1,2,3,4,55,3];
var num2 = num1.slice(1,4);
console.log(num2); //[2, 3, 4]
var num1 = [1,2,3,4,55,3];
var num2 = [‘Marry‘,‘Anda‘,‘Amy‘,‘Leo‘,‘Jeo‘];
console.log(num1.concat(num2)); //[[1, 2, 3, 4, 55, 3, "Marry", "Anda", "Amy", "Leo", "Jeo"]
4.数组拷贝
var num1 = [1,2,3,4,55,3];
var num2 = num1.slice(0);
console.log(num2); //[1,2,3,4,55,3]
console.log(num1 == num2); //false
var num3 = num1.concat();
console.log(num3); //[1,2,3,4,55,3]
console.log(num1 == num3); //false
5.数组元素字符串化
arr.join(separator):返回字符串,这个字符串由数组中的所有元素组成,中间用separator链接
var num1 = [1,2,3,4,55,3];
console.log(num1.join(‘ ‘)); //1 2 3 4 55 3 用空格隔开
console.log(num1.join(‘-‘)); //1-2-3-4-55-3 用‘-‘隔开
6.替换
splice:splice(deletePos,deletCount,item1,...,itemdeleteCount)从指定位置deletePos开始,替换掉指定数目deletCount的元素
var num1 = [1,2,3,4,55,3];
num1.splice(1,2,‘Leo‘,‘Amy‘);
console.log(num1); //[1, "Leo", "Amy", 4, 55, 3]
注:splice和slice的区别:slice会创建一个新数组,而原数组不变;splice会改变原数组
标签:
原文地址:http://www.cnblogs.com/grapefruitskin/p/5366975.html