var pdata = [{ Name: "Apples", Price: 1.99 },{ Name: "Bananas", Price: 2.45 }];
$('#add1').click(function () {
var selected = $('#produceList option:selected').index();
我有一个设置为索引的变量,我希望通过var selected index获取并显示javascript对象
答案 0 :(得分:0)
如果您有索引,则只需
pdata[index];
所以在你的例子中
$('#add1').click(function () {
var index = $('#produceList option:selected').index();
var selected = pdata[index];
})
假设您在问题中给出的代码给出了所选项目的索引。
答案 1 :(得分:0)
<强> HTML 强>
<div class-'item'></div>
<强> JS 强>
$('#add1').click(function () {
var selected = $('#produceList option:selected').index(),
item = pdata[selected];
$('.item').html(item.Name + ', ' + item.Price);
});
<强> JSFIDDLE 强>
答案 2 :(得分:0)
使用简单的数组索引引用配对,因此您的值为:
pdata[0] ---> {Name="Apples", Price=1.99}
pdata[1] ---> {Name="Bananas", Price=2.45}
要获取对象的特定属性,您需要使用属性的名称,因此您的值为:
pdata[0].Name ---> "Apples"
pdata[0].Price ---> 1.99
pdata[1].Name ---> "Bananas"
pdata[1].Price ---> 2.45
因此,要访问所需的信息,一旦检索到索引,就可以使用pdata[index].Name
和pdata[index].Price
。