JavaScript数组:增删改查、排序等

时间:2022-04-08 13:02:02

直接上代码

// 数组应用
var peoples = ["Jack","Tom","William","Tod","Cart","Jhson"];
console.log('原始:'+'length('+ peoples.length +')==' + peoples);
// push(元素),从尾部添加
peoples.push("Smith","Wolf");
console.log('push:'+'length('+ peoples.length +')==' + peoples);
// unshift(元素),从头部添加
peoples.unshift("Anderson");
console.log('unshift:'+'length('+ peoples.length +')==' + peoples);
// pop(),从尾部删除
peoples.pop();
console.log('pop:'+'length('+ peoples.length +')==' + peoples);
// shift(),从头部删除
peoples.shift();
console.log('shift:'+'length('+ peoples.length +')==' + peoples);
// splice(开始,长度),删除
peoples.splice(2,3);
console.log('splice(2,3):'+'length('+ peoples.length +')==' + peoples);
// splice(开始, 长度,元素…),先删除,后插入(当长度为0时,相当于插入;当长度等于元素个数时,相当于替换)
peoples.splice(2,1,"AK-47","91","八一");
console.log('splice(2,1,"AK-47","91","八一")'+'length('+ peoples.length +')==' + peoples);
// concat(数组2)连接两个数组
peoples.concat(["Mini","Coper"]);
console.log('concat(["Mini","Coper"]):'+'length('+ peoples.length +')==' + peoples);
// join(分隔符)用分隔符,组合数组元素,生成字符串,字符串split
peoples.join('-=0=-');
console.log("join('-=0=-'):"+'length('+ peoples.length +')==' + peoples); // sort([比较函数]),排序一个数组,
// 注:排序一个字符串数组和数字数组不同
peoples.sort();
console.log("sort:"+'length('+ peoples.length +')==' + peoples);
var numArr = [12,7,1212,11,318,33];
numArr.sort();
console.log("sort:"+'length('+ numArr.length +')==' + numArr);
numArr.sort(function(n1,n2){
/*
if(n1 < n2){
return -1;
}else if(n1 > n2){
return 1;
}else{
return 0;
}
*/
    //上面的代码简化如下:
return n1 - n2;
});
console.log("sort(function(...)):"+'length('+ numArr.length +')==' + numArr);

链接:

网易云课堂-关于数组讲解