[英]How to store key value pair in array where key is a number
If array is treated as an object and if I create an array called the person and pass on the code如果数组被视为 object 并且如果我创建一个名为 person 的数组并传递代码
var person = []
person.name = "abhishek"
It outputs as它输出为
[name : 'abhishek']
What to write a code to store [ 0:'abhishek']写个代码存什么[0:'abhishek']
I have tried doing我试过做
person["0"]="abhishek"
person.0="abhishek"
But nothing seems to work但似乎没有任何效果
This works great, although, if you're using keys, you should probably use an object, not an array.这很好用,但是,如果您使用键,您可能应该使用 object,而不是数组。
const person = [];
person["name"] = 'fred';
person["age"] = 30;
console.log(person)
console.log(person["name"]); // fred
console.log(person["age"]); // 30
You are assigning values to a key, and you have to use the same key to get the same value.您正在为键分配值,并且必须使用相同的键才能获得相同的值。 This will not work:这行不通:
const person2 = [];
person2["name"] = 'fred';
person2[0]; // undefined
person2["name"]; // fred
If you want the index, just use that, no quote:如果您想要索引,只需使用它,不要引用:
const person3 = [];
person3[0] = 'fred';
person3[5] = 'john';
console.log(person3[0]) // fred
console.log(person3[5]) // john
Try the below solution.尝试以下解决方案。
var person = []; person.push("abhishek"); console.log(person[0]); OR person[1] = "Alok" console.log(person[1]); console.log(person);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.