Index arrays, associative arrays, array-like objects and arrays in Js

Index arrays, associative arrays, array-like objects and arrays in Js

1. Create an array

1.1. Array literal creation

var arr1=[1,2,3];

1.2. Call the constructor to create (there are 3 ways to call)

i. No parameters when calling
var arr=new Array();
该方法创建一个没有任何元素的空数组,等价于[]
1.2. There is a numeric parameter when calling, which specifies the length of the array
var arr=new Array(3);
这种形式可以用来预分配一个存储空间,注意:数组中没有储存值,甚至数组的索引属性,"0" "1"等都还未定义
1.3. Display two or more array elements or a non-numeric element of the array
var arr=new Array(1,2,3,"test")

2. Index array and associative array

Index array: An array whose element index is a number is an index array
Associative array: An array whose element index is a string is an associative array

Actually:

i. There is no index array at the bottom of Js, everything is an associative array, that is to say, the subscripts of all arrays are strings

ii. If you don’t specify the attribute name of the subscript when you add the element, the array is automatically assigned a number.

iii. The standard way of accessing array elements: array object ["subscript name"]

iv. When the subscript name of the element to be accessed is a string: abbreviated as: array object **.** subscript name

v. When the subscript name of the element to be accessed is a number: You cannot use **.** abbreviation, it will be confused with decimals, so it is abbreviated as: array object [number subscript]

3. Array-like objects

Array-like objects have subscript attributes and length attributes, but array-like objects are not of array type, and methods of array type cannot be called directly

3.1. Code example

var students={
    
    
    0:"Lily",
    1:"Alice",
    2:"Jack",
    length:3    
}

3.2. The method of converting an array-like object into an array

var students={
    
    
    0:"Lily",
    1:"Alice",
    2:"Jack",
    length:3    
}
var arr=Array.prototype.slice.call(students) //此方法已多次使用,不再赘述
console.log(arr) //["Lily", "Alice", "Jack"]

4. Objects and Arrays

The bottom layer of all objects in Js is an associative array:

i. Same structure: both are key/value pair structure;

. II same access: can be used [ "attribute name"] or . property value access: Object . property name is the object [ "attribute name"] shorthand object . attribute name are automatically translated to the object [ "attribute name ”];

a. If the attribute name is fixed, there are two ways to access the attribute value;

b. If the attribute name is a variable, you must use [variable], because putting double quotation marks becomes a fixed string.

iii. Access to non-existent variables will not report an error and return undefined;

vi. Forcibly assign values ​​to non-existent attributes, without reporting an error, and automatically add heart attributes at the new location

v. can be traversed by for in

Guess you like

Origin blog.csdn.net/Amazing_rabbit/article/details/108668851