我在javascript中遇到数组问题。 是否可以在同一个数组中插入名称和值
这是我的数组代码
press=new Array('T shirt black - $23','Sweater black - $34','Hoodie shirt black - $87');
这就是我想要的输出
<option value="23">T shirt black - $23</option>
如何将“23”放入数组?
这是完整的代码。对不起,如果我无法解释
答案 0 :(得分:1)
您可以使用对象数组:
press = [
{ desc: 'T shirt black',
price: 23
},
{ desc: 'Sweater black'
price: 34
},
{ desc: 'Hoodie shirt black'
price: 87
}
];
然后,您可以使用press[i].desc
和press[i].price
访问它们。
press.forEach(function(item) {
$('#item').append($('<option/>', {
value: item.price,
text: item.desc+' - $'+item.price
}));
});
这是你小提琴的全部改写。通过将所有不同的数组放入一个键入类别值的对象,我也摆脱了eval()
。
$(document).ready(function () {
dropdowns = {
web: [
{desc: "1 Custom Web Page", price: 39},
{desc: "5 Custom Web Pages", price: 190},
{desc: "10 Custom Web Pages", price: 375},
{desc: "20 Custom Web Pages", price: 710}
],
art: [{desc: '300-word Article x 1', price: 7.00},
{desc: '300-word Article x 5', price: 32.00},
{desc: '400-word Article x 1', price: 8.00},
{desc: '400-word Article x 5', price: 37.00},
{desc: '500-word Article x 1', price: 9.00},
{desc: '500-word Article x 5', price: 40.00},
{desc: '700-word Article x 1', price: 12.00},
{desc: '700-word Article x 5', price: 57.00},
{desc: '1000-word Article x 1', price: 15.00},
{desc: '1000-word Article x 5', price: 70.00}],
blog: [{desc: '300-word Custom Blog x 1', price: 10},
{desc: '400-word Custom Blog x 1', price: 12},
{desc: '500-word Custom Blog x 1', price: 14},
{desc: '300-word Custom Blog x 5', price: 47},
{desc: '400-word Custom Blog x 5', price: 55},
{desc: '500-word Custom Blog x 5', price: 63}
],
press: [{desc: '300-word Custom Press Release', price: 27},
{desc: '400-word Custom Press Release', price: 37},
{desc: '500-word Custom Press Release', price: 47}
]
}
populateSelect();
$(function () {
$('#cat').change(populateSelect);
});
function populateSelect() {
var cat = $('#cat').val();
$('#item').empty();
dropdowns[cat].forEach(function(item) {
$('#item').append($('<option/>', {
value: item.price,
text: item.desc+' = $'+item.price
}));
});
}
});
答案 1 :(得分:0)
最简单的方法是使用entry.split('-')[1];
分割每个条目。之后,该条目将为$23
。修剪它(使用entry.trim()
,并从第二个字符中获取子字符串。这将删除$。
答案 2 :(得分:0)
您可能会使用一组对象(PHP为此使用关联数组;这些也称为哈希映射,以及许多其他不同语言中的许多其他名称):
var clothing = [
{
type: 't-shirt',
color: 'black',
price: 23
},
{
type: 'sweater',
color: 'black',
price: 34
}
]
var i, len = clothing.length;
for (i=0; i<len; i++) {
var obj = clothing[i];
console.log('object at index ' + i + ' of clothing array - ');
for (key in obj) {
console.log(key + ':' + obj[key]);
}
}
输出:
object at index 0 of clothing array -
type:t-shirt
color:black
price:23
object at index 1 of clothing array -
type:sweater
color:black
price:34
答案 3 :(得分:0)
如果数组字符串与数组相同,只能输出,则可以使用split函数。
clothing=new Array('T shirt black - $23','Sweater black - $34','Hoodie shirt black - $87');
for (i=0; i<clothing.length; i++) {
var a = clothing[i].split(" - ");
$('#item').append('<option value = "'+a[1]+'">'+a[0]+'</option>');
}