js数组一些基础使用方法

  • 向数组中添加元素:push
var arr =[];
arr.push("新元素");
  • 删除数组中的指定元素:splice
//删除数组中指定元素“2”
var arr = [1,2,5,8,20,19];
var arr1 = arr.splice(arr.indexOf(2),1);
console.log(arr); //[1, 5, 8, 20, 19]
console.log(arr1); //[2]
  • 数组去重
var arr = [1,2,5,8,5,5,20,19,5];
var temp = new Set(arr);
arr = Array.from(temp);
console.log(arr);// [1, 2, 5, 8, 20, 19] 
  • 数组清空
var arr = [1,2,3];
//方式1
arr = [];
//方式2
arr.length = 0
  • 将数组拼接成字符串
var arr = [1,2,5,8,5,5,20,19,5];
arr = arr.join(",")
console.log(arr); // 1,2,5,8,5,5,20,19,5
  •  数组元素过滤
var arr = [1,2,3];
var arr1 = [1,2,3,4,5,6,7,8];
var newArr = arr1.filter(item => {
    //满足这个条件的元素被保留
    return arr.indexOf(item) == -1;
})
console.log(newArr);//[4,5,6,7,8]
  • 数组遍历
//方式一: 数组名.forEach(function(item,index){})
var arrs=["a","b","c","d","e","f","g"];
arrs.forEach(function(item,index){
  console.log(item);// a b c d e f g ,数组中的元素
   console.log(index);//0 1 2 3 4 5 6,数组中元素所对应的索引
    })
//方式二: for循环
var arrs=["a","b","c","d","e","f","g"];
for(var i = 0; i < arrs.length; i++){
  console.log(arrs.length);
}
//方式三:for of循环
var arrs=["a","b","c","d","e","f","g"];
for(var value of arrs){
  console.log(value);
}

 

你可能感兴趣的:(原生JS)