The principle of the method (. and [] method) of js object to obtain properties

  There are two ways to get properties of js object: 1. By way of . 2. By way of []

  The codes of the two basic methods of obtaining object properties are as follows:

// 通过.方式获取属性值,key是静态的
var a = {name: "zhang", age: 18};
console.log(a.name);
 
// 通过[]获取属性值, key是动态的,可以是字符串,或者数字的形式
var b = {"apple": 3, "pear": 2}
var c = {1: "number1", 2: "number2"}
console.log(b["apple"]);
console.log(c[1]);  // 注意这里的写法跟数组容易混淆,c仍是对象,不是数组
 
// 获取对象所有key的方法
console.log(Object.keys(b));  // 输出[ 'apple', 'pear' ]

Initially, there is not much difference between array and object-related usage methods, because the essence of array and object is to call a variable to view multiple values ​​​​stored.

The main difference between the two is that the subscripts of the array are consecutive numbers, which are stored in the heap memory in order; the objects are not necessarily stored in the order of writing, and the data is mainly obtained through the one-to-one correspondence between key and value

In principle, objects and arrays can be obtained through . or [], but there is a problem with naming conventions

The following explains from the bottom layer that the actual application of the array cannot be used. The reason for obtaining elements

Object/Array. Attribute This method obtains element requirements. The attribute name behind must conform to the js naming convention

                                Because if the array.index, the index is a number, js stipulates that the name cannot start with a number

                                Therefore, if it does not conform to the specification, the array cannot be used to get elements. Get

                                The corresponding length conforms to the naming convention, so the attribute value can be obtained through arr.length

 The following explains from the bottom layer why both arrays and objects can get elements through []

Object/array[attribute][]The number-type attribute in [] will be implicitly converted to a string, so the array.Index can be used

                                So this method can be used to get the elements in the array

                                When object/array [number type], the numeric type will be converted to a string

                                Object/array [variable], will look up properties according to the value stored in the variable

                                Object/array [""], the property name inside may not conform to js specification, such as array index

Guess you like

Origin blog.csdn.net/weixin_46669844/article/details/127972989