写点什么

Web 前端入门:JavaScript 各种数组定义与数组取值方法

  • 2025-05-29
    福建
  • 本文字数:1521 字

    阅读完需:约 5 分钟

数组可以算是程序里面最常用的数据结构了,但凡网页上任何一个列表数据,基本都是以数组的形式存在,像表格、banner 图、菜单列表、商品列表,分类列表等等,在前端领域都是以数组处理。


数组的定义


JS 的数组花样很多,不像其他强类型语言中的数组限制颇多。


数组中的元素


JS 数组中的元素可以是任何类型,包括对象、数组、函数、字符串、数字、布尔值等。而且可以在同一个数组中混合使用各种数据类型。


示例:

const arr1 = [  '前端路引', // 字符串  1, // 数字  true, // 布尔值  function() {}, // 函数  { name: '前端路引' }, // 对象  [1, 2], // 数组  new Date(), // 日期对象  new RegExp(), // 正则对象  // ...还可以是其他各种对象];
复制代码


数组定义


除了使用字面量 [] 定义数组外,还可以使用构造函数 Array 定义数组,也可以使用数组提供的内置方法定义数组。


示例:

const arr1 = [1, 2, 3]; // 字面量定义数组const arr2 = new Array(); // 空数组const arr3 = new Array(1, 2, 3); // 包含元素const arr5 = Array(1, 2, 3) // 与 new Array 一样,获取 [1, 2, 3]const arr6 = new Array(5) // [空属性 × 5]  数组长度为 5const arr7 = Array(5) // 与 new Array(5) 相同const arr8 = Array.of(5) // [5]  数组长度为 1// 将类数组或可迭代对象转为数组const arr9 = Array.from('前端路引') // ['前', '端', '路', '引']const arr10 = Array.from([1, 2, 3], (item) => item * 2) // [2, 4, 6]const arr11 = Array.from({ length: 5 }, (item, index) => index)const arr12 = Array.from(document.querySelectorAll('div'))// 扩展运算符const arr13 = [...arr5]; // 扩展运算符将会展开原数组,获得一个新的数组// fill 方法const arr14 = new Array(5).fill(1); // [1, 1, 1, 1, 1]
复制代码


数组长度


数组的 length 属性表示数组长度,即一个数组中的元素个数,也可以通过 length 属性修改数组长度,如果长度不够,则自动使用 空属性 填充,如果设置的 length 小于原数组长度,则数组将会截断。


const arr1 = [1, 2, 3];console.log(arr1.length); // 3arr1.length = 5; // 自动使用空属性填充console.log(arr1); // [1, 2, 3, 空属性 × 2]arr1.length = 2; // 截断长度为2console.log(arr1); // [1, 2]
复制代码


数组取值


数组取值需要通过 下标(index) 来获取,所有数组下标都从 0 开始,如果下标越界,则会返回 undefined


const arr1 = ['前', '端', '路', '引'];console.log(arr1[0]); // 前console.log(arr1[4]); // undefined 数组最大下标为 length - 1console.log(arr1[-1]); // undefinedconst index = 2;// 可以使用变量取值console.log(arr1[index]); // 路
// 使用 at 方法取值console.log(arr1.at(0)); // 前console.log(arr1.at(4)); // 越界获取 undefined// at 方法负数取值,从数组末尾开始取值倒数,-1 表示数组最后一个元素,-2 表示数组倒数第二个元素,以此类推。console.log(arr1.at(-1)); // 引
复制代码


空属性的取值将会获得 undefined


const arr1 = new Array(5); // [空属性 × 5]  数组长度为 5console.log(arr1[0]); // undefinedconsole.log(arr1.at(0)); // undefined
复制代码


写在最后


以上数组定义和取值基本涵盖了日常开发中最常用的几种方式,当然不是所有的定义方法都能穷举,比如一些歪路子定义数组:


const arr1 = eval(`['前', '端', '路', '引']`);const arr2 = (new Function(`return ['前', '端', '路', '引']`))();
复制代码


歪路子有很多,就不一一介绍了,掌握常用的定义方法即可!


文章转载自:前端路引

原文链接:https://www.cnblogs.com/linx/p/18900100

体验地址:http://www.jnpfsoft.com/?from=001YH

用户头像

还未添加个人签名 2023-06-19 加入

还未添加个人简介

评论

发布
暂无评论
Web前端入门:JavaScript 各种数组定义与数组取值方法_JavaScript_不在线第一只蜗牛_InfoQ写作社区