Home > Web Front-end > JS Tutorial > A brief discussion on Javascript array index_javascript skills

A brief discussion on Javascript array index_javascript skills

WBOY
Release: 2016-05-16 15:48:21
Original
1291 people have browsed it

Let’s start with the title. The reason why it’s not complete is because I’m not going to talk about some things, such as how to use array methods, because you can understand them just by looking at them. What I’ll talk about below are all the things I think are important, and they’re only about arrays. the object itself. In addition, since I don’t have much practical experience in Javascript, there may be some things that I didn’t cover, and some of the content is wrong. Please feel free to give me some advice if you find any problems.

First of all, the array definition of Javascript (hereinafter referred to as js), this is not the point. To put it simply, the following two sentences both create an empty array:

  var arr = [];
  var arr2 = new Array(); // 不写new也可以。
Copy after login

After creation, you can add elements to the array at any time. The size of the array is not fixed and can be added at will like a[0] = 1.

Then we get to the point, about adding elements to the array. First of all, you need to know that an array is an object, and an object is a collection of key-value pairs (similar to map in java, dict in python, and Dictionary in c#). Objects can have attributes, and the functions of objects are called methods. Attributes or methods can be accessed using square brackets or dots. The use of square brackets requires quotation marks. The use of dots can only be used when the attribute name is a legal variable name, that is, the attribute does not contain any Only spaces and hyphens are allowed and do not start with a number. Take 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

Copy after login

Well, this is an object, and there seems to be nothing special about it (except using square brackets to get values), but that’s enough about objects. Let’s start talking about arrays later.

Arrays can do all of the above, that is to say, 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

Copy after login

Because arrays are objects, don’t confuse the string index in square brackets with the usually numeric index. We haven’t started talking about numeric index yet (will talk about it soon).

Different from ordinary objects, the elements of array objects have numerical indexes, or special keys (as mentioned earlier, objects are key-value pairs), which is similar to what we see in other languages ​​such as java, c#, etc. Arrays are the same. In js, this key has some special requirements. It can be a number or a string that can be converted into a number. A reasonable number needs to be an integer ranging from 0 to 4294967295 (2^32-1) ( In fact, this index is treated as a string during lexical analysis. JS converts the string into a 32-bit integer, and then converts the 32-bit integer into a string and compares it with the original string. If they are the same, It means that the index value is a legal number, otherwise it is an ordinary string key). Just give a simple example:

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

  a['2'] = 12;
  console.log(a[2]); // 12

Copy after login

The above code can be run in the browser, and the comments are the output values. This seems to be no different from the arrays we see in other languages. This a['2'] = 12; because '2' is converted to an integer and then converted to a string, it is still '2', so it is the same as a[2]. But in other languages, when we use arrays, we always define a fixed-size array, right? It doesn't seem to be the case 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, an object in js. This is different from other languages ​​(except functional ones such as python). I haven’t studied it in depth, and I can’t explain it clearly. What I understand is that when languages ​​such as C/Java define arrays, they are divided in memory. A fixed-size area is created, and a pointer stores the first address of this area. This does not seem to be the case in js. As mentioned before, arrays are objects and key-value pair structures, so I think arrays in js use hash to store elements, and the memory between elements is not necessarily continuous. of. But I haven't found a way to check the memory address of js variables, so I can't be sure about this. But this is not the focus of this article.

Let’s focus on the index. I mentioned the range of the index earlier, but some students 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 question is, didn’t I say before that the index must be an integer from 0 to 4294967295? Yes, yes, that’s true too. So where is the doubt?

First post two screenshots of the firefox console:


Have you found any problems? When we add elements using normal indexes, the added elements will be printed when printing the array. However, when adding elements using abnormal "indexes", there will be no added elements in the printed array, but look at the right side. Array object, all the added elements are one by one. Look at another picture, this time add a few more elements, and add an attribute to the array (note the element index of the Array object on the right):

I don’t know if you have noticed it. On the right side, the top ones are numeric indexes, which can be printed when printing an array, while the bottom ones are attributes, which will not be printed when printing an array! In other words, in a statement like a[-2] = 2;, this -2 is the key of the attribute, not the key of a special numeric index. When -2 is coerced into a positive integer, it is considered a string. , so this -2 is the same as 4294967296 and 'name', both are the keys of an attribute of the array! So the negative indexes or out-of-range indexes mentioned earlier (should be said to be attribute keys) are legal, and they are all ordinary string keys.

A problem here is that since the key -2 is an ordinary attribute key, some people may ask why an error is reported when using a.-2 or a.'-2' to access the value of the -2 key. And a[-2] will not report an error? Yes, why? When talking about objects earlier, there is a bold sentence: the properties or methods of an object can be accessed using square brackets or periods. When using square brackets to quote, you need to add quotation marks. The period can only be used when the attribute name is a legal one. It can only be used when the variable name is used, that is, when the attribute does not contain any spaces or hyphens and does not start with a number. Therefore, the attributes of keys such as -2 cannot be accessed using the dot notation!

There is also a small problem, that is, square brackets. When we want to access the name attribute of the array, we need to do this: a['name'], that is, name is enclosed in quotes, and -2 is the same as name. For the same attribute key, why can -2 be enclosed in quotes without (or with) quotes? In fact, all characters within square brackets will be regarded as an expression. A simple 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 This is not legal, because it will be regarded as some kind of expression composed of variables x, b, and c. However, it is not certain whether x, b, and c are variables, and the symbols inside are not necessarily supported by js. , so the problem with a[name] is with name, not with []. If it is still difficult to understand, you can imagine name as x y. When x and y are not defined as variables, there must be something wrong with the expression x y, right? Then a[x y] will also have problems, right? There is no problem with a['x y'], because 'x y' is a string.

One thing to add later, in js, variable names can be any combination of numbers, letters, and underscores, and numbers cannot be placed at the beginning. The naming of the object's attribute keys should be looser. If they are legal, they do not need quotation marks. If they are not legal, they can be enclosed in quotation marks.

Okay, that’s all. Let’s summarize: the article first briefly introduces objects, then says that arrays are also objects, finally explains some questions, and then summarizes.

The reason for writing this article is that I watched a js tutorial on Weibo yesterday and had a question about the explanation of arrays. Then the number of words in the comment exceeded 140, so I looked up the information and wrote it out separately. The purpose is to let myself figure it out, and I hope it can help students who are learning js. Array range and index conversion are referred to "Speaking Javascript", other places are my own understanding and opinions.

Finally, thank you for watching. Because it was written in two parts, the sentences may be a little messy. Some places are not messy but the context is complete. Some places have complete context but too much nonsense. In short, that’s it. See you in the next article.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template