0

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

1
  • are you saying that when accessing pricing[11], it should return 160?? like alert(pricing[11]); should alert 160?? Commented Jun 7, 2013 at 13:10

5 Answers 5

2

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

var getPrice = function(arr, index){
    return arr[index > 10 ? 10 : index];
}
Sign up to request clarification or add additional context in comments.

Comments

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

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

2 Comments

You can pass the push function more then one element: array.push(element1, ..., elementN)
Well aware of that, you could store 160 in a variable and then just pass that in 11 times in the push call but six in one and a half dozen of the other
0
i=10;
while(i--) { pricing[i+10] = 160; }

Comments

0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.