我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情
什么是数组
Array对象与其他编程语言中的数组一样,可以将多个项目的集合存储在单个容器中,并具有执行常见数组操作的成员。
声明数组
使用new关键字创建数组
使用new Array, 我们可以指定我们希望存在于数组中的元素,如下所示:
const fruits = new Array("apple", "banana")
console.log(fruits.length)
使用数组字面量创建数组
使用数组字面量声明时,我们可以指定数组的初始值;如果我们不声明任何值,则数组将为空。
const fruits = ["apple", "banana"]
console.log(fruits.length)
Javascript 数组方法
以下是Array对象的方法及其描述
-
forEach
forEach()方法为数组中的每个元素按索引升序调用一次提供的callbach函数。它不会被已删除或者未初始化的索引属性调用
array.forEach(callback[, self])
const array = ["a", "b", "c"] array.forEach(element => console.log(elememt)) // 输出结果为:a, b, c
-
map
Array.map()方法允许遍历数组并使用回调函数修改其元素。然后将在数组的每个元素上执行回调函数。
array.forEach(callback[, self])
let arr = [1,2,3,4] let modifiedArr = arr.map((ele) => { return ele * 3 }) console.log(modifiedArr) // 3, 6, 9, 12
map方法通常用于对元素应用的一些更改,不仅仅局限于上面代码中操作
-
concat
在javascript中,concat()是一个字符串方法,用于将字符串连接在一起。concat()方法将一个或多个字符串值附加到调用字符串,然后将连接的结果作为新的字符串返回。
array.concat(value1, value2, ..., valueN)
const array1 = ["a", "b", "c"] const array2 = ["d", "e", "f"] const array = array1.concat(array2) console.log(array) // 输出: ["a", "b", "c", "d", "e", "f"]
-
push
push方法将给定元素附加到数组的最后一个并返回新数组的长度;当想在数组末尾添加一个元素是,可以使用push()
array.push(element1, ..., elementN)
const cities = ["beijing", "shanghai", "xian"] cities.push("shenzhen") console.log(cities) // ["beijing", "shanghai", "xian", "shenzhen"]
-
pop
pop()方法从数组中删除最后一个元素并将该值返回给调用者。如果在空数组上调用pop(),会返回undefined。
array.pop()
const plants = ["brocoli", "cauliflower", "cabbage", "kale", "tomato"] console.log(plants.pop()) // "tomato console.log(plants) // ["brocoli", "cauliflower", "cabbage", "kale"]
-
splice
splice()方法用于通过在数组的指定位置删除、替换或添加元素来更改数组的内容
array.splice(index, howMany, [element1][, ..., elementN]]
const fruits = ["banana", "orange", "apple", "mango"] fruits.splice(2, 0, "lemon", "kiwi") console.log(fruits) // ['banana', 'orange', 'lemon', 'kiwi', 'apple', 'mango']
-
slice
slice()方法返回从开始到结束(不包含结束)选择的新数组对象中,其中开始和结束表示该数组中项目的索引。原始数组不会被修改
array.slice(begin [, end])
const animals = ["ant", "camel", "duck", "elephant"] console.log(animals.slice(2)) // ["duck", "elephant"] console.log(animals.slice(2, 3) // ["duck"]
-
shift
shift()是一个内置的javascript函数,用于从数组中删除第一个元素。shift()会修改原数组,返回数组中删除的项;shift()函数删除索引位置0处的项目,并将后面的值索引向下移动1
array.shift()
const array1 = [1, 2, 3] const firstElement = array1.shift() console.log(array1) // [2, 3] console.log(firstElement) // 1
-
unshift
unshift()方法将给定值插入到数组对象的开头
array.unshift(element1, ..., elementN)
const array1 = [1, 2, 3] console.log(array1.unshift(4, 5)) console.log(array1) // [4,5,1,2,3]
-
join
join()是一种内置方法,它通过连接数组的所有元素来创建并返回新字符串。join()方法将数组的项连接到字符串中并返回改字符串。指定的分隔符将分隔元素数组。默认分隔符是(,)
array.join(separator)
const elements = ["fire", "air", "water"] console.log(elements.join()) // "fire,air,water" console.log(elements.join("")) // "fireairwater" console.log(elements.join("-")) // "fire-air-water"
end! 到目前位置,我们已经讲了关于数组的10个不同的用法,下一篇,我们会将关于数组更高级的一下api的用法