当前位置:网站首页>JS some small problems about adding and accessing values to arrays

JS some small problems about adding and accessing values to arrays

2022-06-25 18:36:00 ookaoooo

Some small problems about adding and accessing values to arrays

Today, let's take a look at some small problems about arrays , It may help you a little , Of course, if I say something wrong, I'm also welcome to give advice , After all, I am also a rookie .

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

If we want to add a value to the array , With [] In the form of , If you write a negative number or a string, it adds... To the end of the array , And it is added in the form of key value pairs , So the next time you access this value, you can access it in the form of points , But if it is a number, it must pass [] visit .

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

If you add a value to an array through a string or a negative number , The next time you access it, you must also access it in the form of key value pairs

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

It is worth noting that values added by strings or negative numbers , That array will not add its length , And those added in this way will always be at the end of the array , Because we use push Method to add a number 4 We found that it didn't add "is" to the end , Everybody knows push Method to add a value to the end of the array . Maybe we can draw a conclusion that is numbers and their arrangement , Key value pairs and key value pairs are arranged .

Update array small problem .

num.push(4,3,5); >> The return value is the last number added, that is, the number 5
num.reverse(); >> Array in reverse order , Not by size , It's the other way around 
console.log(num) >>[5, 3, 4]</pre>
num[5,"a",0]="111"; >>["111"]  If the end says 0 Or array length plus 1 Well, as usual .
console.log(num);</pre>
num[5,"a",6]="111";
console.log(num);  >>[6: "111"]</pre>

The back covers the front , The index written to the last bit cannot be greater than the length of the array +1, Otherwise, whether you write numbers or not, they are added through key value pairs , If it's negative, it's the same .

a[10] = 10;
console.log(a); >>[10: 10]
console.log(a.length); >>11
console.log(a[0]); >>undefined
console.log(a[10]); >>10</pre>

If the length of the array is 0 Or not as long as the index you want to add , that js All previous values will be set to undefined, And it is added in the form of key value pairs .

原网站

版权声明
本文为[ookaoooo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190529472168.html