zoukankan      html  css  js  c++  java
  • 关于数组添加值和访问值的一些小问题

    今天来看看关于数组方面的一些小问题,可能对你会有一些小小的帮助,当然如果我有说错的地方也欢迎指教,毕竟我也是一个菜鸟。

     1.

    1 // var arr = [1,2,3];
    2 // arr["bbb"]="nor 1";
    3 // arr[-2]="nor 2";
    4 // console.log(arr);    >> [1, 2, 3, bbb: "nor 1", -2: "nor 2"]
    5 // console.log(arr.bbb)    >>    "nor 1"

    如果我们想往数组里面添加一个值,以[]的形式添加,如果写的是负数或者字符串那么它是在数组的末尾添加,并且它是以键值对的形式添加的,所以下次访问这个值的时候可以使用点的形式访问,但是如果是数字必须通过[]访问。

    2.

    1 // var arr = [1,2,3];
    2 // arr["bbb"]="nor 1";
    3 // console.log(arr);    [1, 2, 3, bbb: "nor 1"]
    4 // console.log(arr[3])    undefined

    如果通过字符串或者负数往数组里面添加一个值,那么下次访问的时候也必须通过键值对形式访问

    3.

    1 // var arr = [1,2,3];
    2 // arr["bbb"]="nor 1";
    3 // arr[-2]=222;
    4 // arr.push(4);
    5 // console.log(arr);    >>    [1, 2, 3, 4, bbb: "nor 1"]
    6 // console.log(arr.length);    >> 4

    // 值得注意的是通过字符串或者负数添加的值,那个数组是不会添加它的长度的,并且使用这种方式来添加的永远会在数组的最后面,因为我们使用push方法添加数字4的时候我们发现它并没有把是添加到最后后面,大家都知道push方法的将值添加到数组的末尾的。也许我们可以得出一个结论那就是数字和数字排列,键值对与键值对排列。

    更新数组小问题。

    1 // var num = [];
    2 // num.push(4,3,5); >>返回值是添加的最后那个数也就是数字5
    3 // num.reverse(); >>数组倒序排列,不是按照大小,是反过来
    4 // console.log(num) >>[5, 3, 4]
    1 var num = [];
    2 num[5,"a",0]="111"; >>["111"] 如果末尾写的是0或者数组长度加1那么和正常情况一样。
    3 console.log(num);
    1 var num = [];
    2 num[5,"a",6]="111";
    3 console.log(num);  >>[6: "111"]

    // 后面的会把前面的覆盖,最后一位写的索引不能大于数组长度+1,否则不管你写的是不是数字都是通过键值对的方式添加,如果是负数也是一样的。

    1 // var a = [];
    2 // a[10] = 10;
    3 // console.log(a); >>[10: 10]
    4 // console.log(a.length); >>11
    5 // console.log(a[0]); >>undefined
    6 // console.log(a[10]); >>10

    // 如果数组的长度是0或者没有你要添加的那个索引那么长,那么js会把之前的值全部设置成undefined,并且用键值对的形式添加的。

  • 相关阅读:
    16. 3Sum Closest
    17. Letter Combinations of a Phone Number
    20. Valid Parentheses
    77. Combinations
    80. Remove Duplicates from Sorted Array II
    82. Remove Duplicates from Sorted List II
    88. Merge Sorted Array
    257. Binary Tree Paths
    225. Implement Stack using Queues
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/pssp/p/5184088.html
Copyright © 2011-2022 走看看