Michael Fitzgerald
Michael Fitzgerald

Reputation: 37

jQuery Number array, everything above a certain number

I have a pricing array

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;

Everything below 10 has a price, everything above 10 will have the same price as ten

It only goes to 20 so what i did originally was just repeat the price for 11 - 20. But thats wasteful, how can I tell me array that everything > 10 = 160

p.s my final version of this is condensed :)

Upvotes: 0

Views: 78

Answers (5)

JustinMichaels
JustinMichaels

Reputation: 1092

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);
}

I also made a JSFiddle for this.

@CD was stating that the push function can take multiple items to append to the array. The code would look like this then:

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);

Upvotes: 1

BeNdErR
BeNdErR

Reputation: 17927

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);

Upvotes: 0

gpojd
gpojd

Reputation: 23065

You missed the first entry in your array (since it is 0 based). I would change it to this:

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;

Then you can set the last 10 using this:

for(var x = 10; x < pricing.length; x++) {
    pricing[x] = pricing[9];
}

Example fiddle.

Upvotes: 0

CD..
CD..

Reputation: 74156

You can leave your array as is and use a function like:

var getPrice = function(arr, index){
    return arr[index > 10 ? 10 : index];
}

Upvotes: 2

mishik
mishik

Reputation: 10003

i=10;
while(i--) { pricing[i+10] = 160; }

Upvotes: 0

Related Questions