laiquanfeng

有一些数组方法是ECMAScript新增的,一定要注意浏览器的兼容!!

Array对象属性:

属性 说明

constructor

返回对创建此对象的函数引用
length 返回集合内的元素的所有长度
prototype 向对象添加属性和方法

 

constructor

const arr = [1, 2, 4, 5, 6, 9, 15]
console.log(arr.constructor)

//输出为  ƒ Array() { [native code] }

length

const arr = [1, 2, 4]
console.log(arr.length)

//输出为  3

 

下文的箭头函数的解释为:x => x*1  ==  function(x){return x*1}

如果是有多个参数则:(x,y) => x*y  ==  function(x,y){return x*y}  。我这只是为了简写,并不代表适用。

 

Array对象方法:

方法 说明
shift() 删除第一个元素,并返回结果。
unshift() 插入元素至第一个元素前面,括号内放入要插入的元素。
splice()  向数组内添加新元素。第一个参数定义添加新元素的位置,以拼接的方式,第二个参数是定义应删除多少个元素
slice()  找出数组内的指定元素。第一个参数定义删除元素的位置,第二个参数是结束位置。
pop() 删除数组内的最后一个元素,并返回结果。
push() 在数组内的末尾添加一个或多个元素,并返回结果。
reverse() 反转数组内的元素顺序,并返回结果。
toString() 把数组转换为字符串并返回结果。注意:S为大写。
concat() 合并(连接)数组创建一个新数组,也可以将括号内的值作为参数合并至当前数组。
sort() 对数组内的元素进行排序。 (排序的依照我还搞不清楚....)
valueOf() 返回数组对象的原始值。
join()  把数组内的元素拼成字符串,再以指定的分隔符进行分隔。
isArray() 判断对象是否是一个数组。
includes() 判断数组内是否包含指定的值,可添加多个。
lastIndexOf() 返回指定的元素最后出现的位置。
find() 返回数组内通过条件的第一个元素。注意:用函数判断、如果没有符合条件的元素则返回undefined。
indexOf() 返回指定元素在数组内的位置。
copyWithin() 指定元素位置拷贝到另一个位置。注意:后面的元素会被位移出数组,慎用!

shift()

const myArray = [3, 1, 5, 2, 6]
console.log(myArray.shift())

//输出为 3

unshift()

const myArray = [3, 1, 5, 2, 6]
console.log(myArray.unshift(1,3,2323))

//输出为 [1, 3, 2323, 3, 1, 5, 2, 6]

splice()

const myArray = [3, 1, 5, 2, 6]
console.log(myArray.splice(1,1,'浮云共我归'))

//输出为  [3, "浮云共我归", 5, 2, 6]

slice()

const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(arr2.slice(2, 4))

//输出为  (2) [3, 4]

pop()

const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(arr2.pop())

//输出为  9

push()

const arr2 = [1, 2, 3, 4]
console.log(arr2.push('233','333'))
console.log(arr2)

//输出为  6  、  (6) [1, 2, 3, 4, "233", "333"]

toString()

const myArray = [3, 1, 5, 2, 6]
console.log(myArray.toString())

//输出为  3,1,5,2,6

concat()

const myArray = [3, 1, 5, 2, 6]
const MyArray = [66,77]
const result = myArray.concat(MyArray)
console.log(result.concat('add'))

//输出为  [3, 1, 5, 2, 6, 66, 77, "add"]

sort()

const arr2 = [6, 2, '云', 1, 4, 'a']
const result = arr2.sort((x, y) => {
    if (x > y) {
        return 1
    }
    if (x < y) {
        return -1
    }
    return 0
})
console.log(result)

//输出为  (6) [1, 2, 4, 6, "a", "云"]

valueOf()

const arr2 = [6, 2, '云', 1]
console.log(arr2.valueOf())
            
// 输出为  (4) [6, 2, "云", 1]

join()  (结合split()方法会有意想不到的结果,而且我发现)

const arr2 = ['浮','云','共','我','归']
console.log(arr2.join(
'

分类:

技术点:

相关文章:

  • 2021-09-03
  • 2021-12-30
  • 2021-11-05
  • 2021-10-12
  • 2021-08-13
  • 2022-02-02
猜你喜欢
  • 2021-11-30
  • 2018-12-20
  • 2021-08-09
  • 2022-02-20
相关资源
相似解决方案