我有一个定价数组
pricing = new Array();
pricing[1] = 35;
pricing[2] = 60;
pricing[3] = 84;
pricing[4] = 104;
pricing[5] = 120;
pricing[6] = 132;
pricing[7] = 140;
pricing[8] = 144;
pricing[9] = 153;
pricing[10] = 160;
10以下的所有商品都有价格,10以上的价格都与10相同。
它只有20,所以我最初做的只是重复11 - 20的价格。但那太浪费了,我怎么能告诉我阵列一切> 10 = 160
p.s我的最终版本是精简的:)
答案 0 :(得分:2)
您可以按原样保留数组,并使用如下函数:
var getPrice = function(arr, index){
return arr[index > 10 ? 10 : index];
}
答案 1 :(得分:1)
var pricing = [], i;
pricing.push(35);
pricing.push(60);
pricing.push(84);
pricing.push(104);
pricing.push(120);
pricing.push(132);
pricing.push(140);
pricing.push(144);
pricing.push(153);
for (i = 0; i < 11; i++) {
pricing.push(160);
}
我也为此做了JSFiddle。
@CD表示push function可以将多个项目附加到数组中。代码看起来像这样:
var pricing = [], value = 160;
pricing.push(35);
pricing.push(60);
pricing.push(84);
pricing.push(104);
pricing.push(120);
pricing.push(132);
pricing.push(140);
pricing.push(144);
pricing.push(153);
pricing.push(value, value, value, value, value, value, value, value, value, value, value);
答案 2 :(得分:0)
i=10;
while(i--) { pricing[i+10] = 160; }
答案 3 :(得分:0)
pricing = new Array();
var arraySize = 100;
pricing[1] = 35;
pricing[2] = 60;
pricing[3] = 84;
pricing[4] = 104;
pricing[5] = 120;
pricing[6] = 132;
pricing[7] = 140;
pricing[8] = 144;
pricing[9] = 153;
for(var x = 10; x < arraySize; x++)
pricing[x] = 160
console.log(pricing);
答案 4 :(得分:0)
您错过了数组中的第一个条目(因为它基于0)。我会改变它:
pricing = new Array(20);
pricing[0] = 35;
pricing[1] = 60;
pricing[2] = 84;
pricing[3] = 104;
pricing[4] = 120;
pricing[5] = 132;
pricing[6] = 140;
pricing[7] = 144;
pricing[8] = 153;
pricing[9] = 160;
然后你可以用这个来设置最后10个:
for(var x = 10; x < pricing.length; x++) {
pricing[x] = pricing[9];
}