[英]Array Push uses the same index for the same value in JavaScript
I just found out that using the function array.push(value) using the same value name, will give the same index of the first item with the same value name. 我刚刚发现,使用具有相同值名称的函数array.push(value)将给具有相同值名称的第一项提供相同的索引。
Look at the example code following: 查看以下示例代码:
<p>Click the button to add a new element to the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.push("Orange");
var orange_index = fruits.indexOf("Orange");
document.getElementById("demo").innerHTML = orange_index;
}
</script>
If you run it, you will notice that the answer is "1" , that corrisponds to the first "Orange" item inserted into the array. 如果运行它,您会注意到答案是“ 1”,它对应于插入到数组中的第一个“ Orange”项。
How can I avoid this behaviour ? 如何避免这种行为? I need to insert the same values into an array with different indexes. 我需要将相同的值插入具有不同索引的数组中。
Do I need to use multidimensional array ? 我需要使用多维数组吗? I have a deck of cards, and I need to store the ranks and suits in array. 我有一副扑克牌,我需要将军衔和西服存储在阵列中。 So far I created two different arrays for ranks and suits, but I'm having this problem. 到目前为止,我为等级和西服创建了两个不同的数组,但是我遇到了这个问题。 I retrieve the ranks and suits separately, should I push them together into a new multidimensional array? 我分别检索等级和花色,是否应该将它们一起推入新的多维数组? how ? 怎么样 ?
Thanks 谢谢
Example fiddle . 小提琴的例子 。
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. indexOf()方法返回可以在数组中找到给定元素的第一个索引;如果不存在,则返回-1。
Your array looks like following after you clicking in button : 单击按钮后,数组如下所示:
["Banana", "Orange", "Apple", "Mango", "Orange"]
So when you try : 因此,当您尝试:
var orange_index = fruits.indexOf("Orange");
That will return the first index of Orange
like you saw in description, so normally it will return 1
. 就像您在描述中看到的那样,它将返回Orange
的第一个索引,因此通常它将返回1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.