js中定义数组的两种方式 js中定义数组的方法


js中定义数组的两种方式 js中定义数组的方法

文章插图

Array.fill().fill() 方法是用一个固定值填充一个数组中的元素 , 从起始索引到终止索引内的全部元素 , 即将数组中的所有元素更改为另外的值 , 从开始索引(默认为 0)到结束索引(默认为 array.length) , 最终返回修改后的数组 。
【js中定义数组的两种方式 js中定义数组的方法】语法:Array.fill(value,start,end)
  • value:为需要处理的数组
  • start:开始索引(默认为 0)
  • end:结束索引(默认为 array.length) , 如指定结束索引 , 是不包括索引本身的元素
const articles = ["《如何在 Vue 的计算属性中传递参数》作者:天行无忌","《Angular数据状态管理框架:NgRx/Store》作者:天行无忌","《Angular管道PIPE介绍》作者:天行无忌",];const replaceArticle ="《JavaScript 数组操作必须熟练运用的10个方法》作者:天行无忌";console.log([...articles].fill(replaceArticle, 1)); // 从索引为 1 的元素开始的素有元素替换 , /*['《如何在 Vue 的计算属性中传递参数》作者:天行无忌','《JavaScript 数组操作必须熟练运用的10个方法》作者:天行无忌','《JavaScript 数组操作必须熟练运用的10个方法》作者:天行无忌']*/console.log([...articles].fill(replaceArticle, 1, 2)); // 从索引为 1 的开始到索引为2的元素替换 , 不包括索引为2的元素在内/* ['《如何在 Vue 的计算属性中传递参数》作者:天行无忌','《JavaScript 数组操作必须熟练运用的10个方法》作者:天行无忌','《Angular管道PIPE介绍》作者:天行无忌']*/Array.from().from() 方法从一个类似数组或可迭代对象创建一个新的 , 浅拷贝的数组实例 。
语法:Array.from(arrayLike,mapFn)
  • arrayLike:想要转换成数组的伪数组对象或可迭代对象
  • mapFn:可选 , 如果指定了该参数 , 新数组中的每个元素会执行该回调函数
console.log(Array.from([1, 2, 3], (item) => item + item)); // [ 2, 4, 6 ]console.log(Array.from("china")); // [ 'c', 'h', 'i', 'n', 'a' ]使用方法这里大概介绍一下 Array.fill() 和 Array.from() 的使用方法 , 但不限于本文介绍 。
创建数组并赋值这里介绍几种创建于数组并赋值的方法 , 首先可以使用 Array.fill 方法创建一个填充有值的数组 , 但一般是同值数组 。
const numbers = new Array(5).fill(1);console.log(numbers); // [ 1, 1, 1, 1, 1 ]上面创建了一个全是 1 的 5 维数组 , new Array(5) 创建一个有 5 维数组 , 再适用 .fill() 将每维替换为 1。
可以通过对一个空数组调用 keys 方法 , 生成一个升序的数组 , 如下:
const numbers = [...new Array(5).keys()];console.log(numbers); // [ 0, 1, 2, 3, 4 ]还可以用 Array.from() 和一些计算方法来填充一个数组 , 如下:
const numbers = Array.from(new Array(5), (_, i) => i ** 2);console.log(numbers); // [ 0, 1, 4, 9, 16 ]上面创建了一个 0-4 的数字平方组成的数组 , 如果需要创建 undefined 组成的数组 , 如下:
const undefineds = [...new Array(3)];console.log(undefineds); // [ undefined, undefined, undefined ]创建重复值在JavaScript 中创建重复值 , 常见有四种方式:
  • 使用循环
  • 使用 Array.fill()
  • 使用 repeat()
  • 使用 Array.from()
repeat()构造并返回一个新字符串 , 该字符串包含被连接在一起的指定数量的字符串的副本 。


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: