• 《现代 JavaScript 教程 》Array


    JavaScript的 Array 对象是用于构造数组的全局对象,数组是类似于列表的高阶对象。(引用自MDN)

    相较于其它数据类型,它具有以下几个特点:

      1、提供了遍历和修改元素的操作。

      2、数组长度和元素类型都不固定,并且数据在内存中并不要求连续。所以相较于C++等语言中的数组,它更类似于C++中的deque,如果你想使用连续的数组可以使用TypedArray

      3、只能用整数作为数组元素的索引,而不能用字符串。

    数组的常见操作:

    1、创建数组

    let fruits = ['Apple', 'Banana']
    
    console.log(fruits.length)
    //length属性是数组的长度,准确地说,它是数组最后一个数字索引值加一。它由数组方法自动调整。
    //如果我们手动缩短 length,那么数组就会被截断。
    // 2
    //let fruits = new Array();
    new Array()创建了一个对象,新建的对象a.__proto__ == Array.prototype。
    这是一个标准的由Class到实例的创建步骤。体现了JS在面向对象方面向主流语言的过度。
    
    //let fruits = Array();和new Array完全相同

    2、通过索引访问数组元素

    let first = fruits[0]
    // Apple
    
    let last = fruits[fruits.length - 1]
    // Banana

    3、遍历数组

    fruits.forEach(function(item, index, array) {
      console.log(item, index)
    })
    // Apple 0
    // Banana 1

    4、添加元素到数组的末尾

    let newLength = fruits.push('Orange')
    // ["Apple", "Banana", "Orange"]

    5、删除数组末尾的元素

    let last = fruits.pop() // remove Orange (from the end)
    // ["Apple", "Banana"]

    6、删除数组头部元素

    let first = fruits.shift() // remove Apple from the front
    // ["Banana"]

    7、添加元素到数组的头部

    let newLength = fruits.unshift('Strawberry') // add to the front
    // ["Strawberry", "Banana"]

    8、找出某个元素在数组中的索引

    fruits.push('Mango')
    // ["Strawberry", "Banana", "Mango"]
    
    let pos = fruits.indexOf('Banana')
    // 1

    9、通过索引删除某个元素

    let removedItem = fruits.splice(pos, 1) // this is how to remove an item
    
    // ["Strawberry", "Mango"]

    10、从一个索引位置删除多个元素

    let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']
    console.log(vegetables)
    // ["Cabbage", "Turnip", "Radish", "Carrot"]
    
    let pos = 1
    let n = 2
    
    let removedItems = vegetables.splice(pos, n)
    // this is how to remove items, n defines the number of items to be removed,
    // starting at the index position specified by pos and progressing toward the end of array.
    
    console.log(vegetables)
    // ["Cabbage", "Carrot"] (the original array is changed)
    
    console.log(removedItems)
    // ["Turnip", "Radish"]

    11、复制一个数组

    let shallowCopy = fruits.slice() // this is how to make a copy
    // ["Strawberry", "Mango"]
  • 相关阅读:
    LVM
    Linux 压缩归档
    <基础> PHP 字符串操作
    <基础> PHP 数组操作
    PHP 文件操作类(转载)
    Linux 磁盘管理(分区、创建文件系统、挂载)
    文件系统(File System)
    Linux 硬链接、软链接
    Django基础一
    数据库约束
  • 原文地址:https://www.cnblogs.com/GodZhuan/p/15484313.html
Copyright © 2020-2023  润新知