如果数组被视为对象,并且如果我创建了一个名为person的数组并传递代码
var person = []
person.name = "abhishek"
输出为
[name : 'abhishek']
写什么代码来存储[0:‘abhishek’]
我试过做
person["0"]="abhishek"
person.0="abhishek"
但似乎什么都不起作用
这非常有效,尽管如果使用键,可能应该使用对象,而不是数组。
const person = [];
person["name"] = 'fred';
person["age"] = 30;
console.log(person)
console.log(person["name"]); // fred
console.log(person["age"]); // 30
您正在为键赋值,您必须使用相同的键才能获得相同的值。这将不起作用:
const person2 = [];
person2["name"] = 'fred';
person2[0]; // undefined
person2["name"]; // fred
如果你想要索引,就用它,没有报价:
const person3 = [];
person3[0] = 'fred';
person3[5] = 'john';
console.log(person3[0]) // fred
console.log(person3[5]) // john
尝试以下解决方案。
var person = [];
person.push("abhishek");
console.log(person[0]);
OR
person[1] = "Alok"
console.log(person[1]);
console.log(person);