Javascript array index_javascript tips-js tutorial

Source: Internet
Author: User
Tags array definition
This article mainly introduces the Javascript array index, which is a summary of some of my personal experience. If you need it, you can refer to the following questions. The reason is incomplete, this is because I am not going to talk about how to use the array method, for example, because I will talk about the array object itself. In addition, because I have little practical experience in Javascript, some things may not be involved, and some content is incorrect. Please kindly advise those who have found the problem.

First, the array definition of Javascript (js) is not the focus. To put it simply, the following two statements are to create an empty array:

Var arr = []; var arr2 = new Array (); // do not write new.

After creation, you can add elements to the array at any time. The array size is not fixed. You can add it as if a [0] = 1.

Next, let's focus on adding elements to the array. First, you need to know that the array is an object, and the object is a set of key-value pairs (similar to map in java, dict in python, Dictionary in c ), an object can have attributes, and its functions are called methods. The attributes or methods of an object can be accessed using square brackets or periods. The reference using square brackets must be enclosed by quotation marks, the dot number can only be used when the attribute name is a valid variable name, that is, the attribute does not contain any space characters and does not start with a number, let's look at an example:

  var person = {};  person.age = 22;  person.sayhi = function(){console.log('hi');};  person.age; // 22  person['age']; // 22  person.sayhi(); // hi  person['sayhi'](); // hi

Well, this is the object, and it seems that there is nothing special (except the square brackets), but it is enough to say something about the object, and the array will be introduced later.

For the above, the array can all be done, that is, the following code can also run normally (only the first line is different from the above ):

  var person = [];  person.age = 22;  person.sayhi = function(){console.log('hi');};  person.age; // 22  person['age']; // 22  person.sayhi(); // hi  person['sayhi'](); // hi

Because arrays are objects, we should not mix string indexes in square brackets with the numeric indexes. We haven't started to talk about digital indexes.

Unlike an ordinary object, the elements of an array object have a digital index or a special key (as mentioned above, the object is a key-Value Pair ), this is the same as the array we see in other languages such as java and c. In js, this key has some special requirements. It can be a number, a string that can be converted to a number, and a reasonable number, it must be an integer ranging from 0 to 4294967295 (2 ^ 32-1) (in fact, this index is used as a string during lexical analysis, js converts the string to a 32-bit integer, and then converts the 32-bit integer to a string to compare it with the original string. If it is the same, it indicates that the index value is a valid number, otherwise it is a normal string key ). For example:

  a = [1, 3, 5, 7];  console.log(a[0]); // 1  console.log(a['0']); // 1  a['2'] = 12;  console.log(a[2]); // 12

The above code can be run in the browser, and the comment is the output value. This is no different from the array we see in other languages. This a ['2'] = 12; Because '2' is converted to an integer and then converted to a string or '2', it is the same as a [2. However, in other languages, we use arrays to define a fixed-size array, right? It doesn't seem like a ha here, and the index range of the array is also mentioned here. So why? The simple answer is that the array here is an object, which is an object in js. This is different from other languages (except for functions such as python). I have not studied it in depth, but I do not know it clearly. What I understand is, when c/java and other languages define arrays, a fixed size area is divided in the memory, and a pointer stores the first address of this area. In js, it seems that this is not the case. As mentioned above, arrays are objects and key-value pairs. Therefore, arrays in js are stored in hash mode, the memory between elements is not necessarily continuous. However, I have not found a method to view the memory address of the js variable, so I cannot determine this. However, this is not the focus of this article.

We put the focus on the index. we mentioned the index scope above, but some people may try it, that is, a [-1] = 2; or a [4294967296] = 10; there is no problem with this statement. Yes, this is not an error. This is a normal statement and of course there will be no problem. But the problem is that the index must be an integer ranging from 0 to 4294967295? Yes, that's right. Where is the question?

Paste the following two images on the firefox console:


Have you found any problems? When we use a normal index to add elements, when printing an array, the added elements will be printed, and when we use an abnormal "Index" to add elements, no elements are added to the printed Array, but you can see the Array object on the right, but there are a lot of elements added. Let's look at another figure. add several more elements and add an attribute to the Array (see the element index of the Array object on the right ):

I wonder if you have found out. On the right side, the numbers above are numeric indexes, which can be printed when the array is printed. The following are attributes, and the printed array does not print attributes! That is to say, a [-2] = 2; in this statement,-2 is the attribute key rather than the key of a special digital index. When-2 is forcibly converted to an integer, it is considered as a string, so like-2 and 4294967296 and 'name', it is the key of an attribute of the array! Therefore, the negative index or out-of-range index (attribute key) mentioned above are valid, and they are common string keys.

The problem here is that since-2 is a common property key, some people may say why. -2 or. '-2' the value of the access-2 key will report an error, and a [-2] will not report an error? Yes, why? When talking about objects, there is a bold sentence: the attributes or methods of objects can be accessed using square brackets or dot numbers, where square brackets are used to reference objects with quotation marks, point numbers can be used only when the attribute name is a valid variable name, that is, the attribute does not contain any space characters and does not start with a number. Therefore, the-2 key attribute cannot be accessed by the DoT number!

Another small problem is square brackets. When we want to access the name attribute of the array, we need to set a ['name'], that is, the name is enclosed in quotation marks, -2 is the key of the same attribute as name. Why can-2 be enclosed in quotation marks? In fact, all characters in square brackets are treated as an expression. A single number-2 is a legal expression, but if name is not defined as a variable name, name is not a legal expression. Similarly, x ^ B & c is not legal because it will be treated as an expression composed of variables x, B, and c, however, whether x, B, and c are variables is unknown, and the symbols in it are not necessarily supported by js. Therefore, the problem of a [name] lies in name rather. If you still cannot understand it, you can think of name as x + y. When x and y are not defined as variables, the expression x + y must be incorrect, right? Then a [x + y] may have problems, right? A ['x + y'] is no problem, because 'x + y' is a string.

In JavaScript, the variable names can be composed of numbers, letters, and underscores. The numbers cannot be placed in the start position. The name of the property key of the object should be loose. Valid values can be enclosed without quotation marks. Otherwise, they can be wrapped in quotation marks.

Now, let's make a conclusion. The article first briefly introduces the object, then the array is also the object, finally explains some questions, and then summarizes.

The reason for writing this article is that I read a js tutorial on Weibo yesterday, raised a question about the array explanation, and then the number of comments exceeds 140, so I wrote the information separately. The goal is to help you understand and learn about js. Array range and index conversion refer to Speaking Javascript, which is understood and viewed by others.

Finally, thanks for watching. Because the statements are written twice, the statements may be messy, the context is complete, and the context is complete, but there are too many nonsense. In short, let's do it. For more information, see.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.