javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS数组

JavaScript数组操作总结

作者:爱思考的猪

JavaScript中的Array对象与其他编程语言中的数组一样,是一组数据的集合。在JavaScript中,数组里面的数据可以是不同类型的,并具有用于执行数组常见操作的方法,本文整理了一些常用的,需要的可以参考一下

1.定义

数组是按次序依次排列的一组值

const arr = [0,'1',{},function(){}];
//二维数组
const arr1 = [1,2,[3,4,5],6];

2.数组的本质

数组是一种特殊的对象,数组的key是正整数字符串,我们一般使用数字键操作数组,会自动转换成字符串

const arr = [];
arr['1'] = 1;
//1被自动转换成'1'
console.log(arr[1],arr['1']); //1
typeof arr; //obejct

3.数组的length

数组的length计算的是数组中正整数的个数,但你依然可以将数据的key设置为其它类型的值,不过这不会增加length的长度

const arr = [];
arr[2.1] = 2.1;
arr['a'] = 'a';
console.log(arr); //[2.1: 2.1, a: 'a']
console.log(arr.length); //0

length是可写的

const arr = [1,2,3,4,5];
arr.length = 2;
console.log(arr); //[1,2]

4. in

in关键用来判断数组中存在某个键,可应用于数组和对象

const arr = ['a','b'];
1 in arr; // true
2 in arr; //fasle

5. for…in

const arr = [1,2];
arr['a'] = 3;
arr[4.5] = 4;
for(key in arr){
 console.log(key);
};
// 0
// 1
// a
/  4.5
Object.keys(arr); // ['0', '1', 'a', '4.5']

6.数组的空位

var arr = [1,5,,8];
console.log(arr); //[1, 5, empty, 8]
//使用delete也会产生空值
delete arr [0];
console.log(arr); //[empty, 5, empty, 8]
console.log(arr.length); //4
    const arr1 = new Array(10); //[empty × 10]
    for (key in arr1) {
      console.log(arr1);
    }; //无输出,没有进行遍历
    arr1.forEach((v) => {
      console.log(v)
    }); //无输出,没有进行遍历
    console.log(Object.keys(arr1)); //[]
    const arr2 = [undefined, undefined, undefined]; //[empty × 10]
    for (key in arr2) {
      console.log(key);
    };
    //0
    //1
    //2
    arr2.forEach((value, index) => {
      console.log(value, index)
    });
    // undefined,0
    // undefined,1
    // undefinef,2
    console.log(Object.keys(arr2)); //[3]
    // 使用for循环遍历empty
    for(let i = 0;i<arr1.length;i++){
       console.log(arr1[1])
    };
    //undefined × 10

7.类数组(伪数组)

类数组的定义:键名都是正整数或零,拥有length属性

const arrayLike = { 
  0:'a', 
  1:'b', 
  2:'c', 
  length:3 
  };
arrayLike[3] = 'd';
console.log(arrayLike[0]); //a
console.log(arrayLike.length); //3

上面的代码为arrayLike添加了一个数字键,但length没有改变,这就说明arrayLike不是数组

典型的类数组有函数的arguments、大多数的元素DOM集合、字符串

function foo(){
  console.log(arguments);
};
foo('tom','jack');
// {0:'tom', 1:'jack', length:2, callee:...}
console.log(document.getElementsByClassName('a'));
//{"0": ...,"1": ...,"2":..., "length":3}
const str = 'apple';
console.log(str.length); //5
consoel.log(str[2]); //p

将伪数组转为数组

function foo(){
  const arr = Array.prototype.slice.call(arguments);
}
function foo(){
  const arr = [...arguments]
}
function foo(...args){
}

总结

到此这篇关于JavaScript数组操作总结的文章就介绍到这了,更多相关JS数组内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文