views:

43

answers:

5

I have a dynamically generated large string witch I am splitting.

var myString="val1, val, val3, val4..... val400"

I do a simple split on this string:

myString= myString.split(',')

getting the following:

myString[1] // gives val1
myString[2] // gives val2
myString[3] // gives val3
.
.
.
myString[400] // gives val400

Is there a way to make the following:

myString[101] // gives val1
myString[102] // gives val2
myString[103] // gives val3
.
.
.
myString[500] // gives val400

Thank you.

+3  A: 

Arrays are zero-based, so in fact in your version you have indices 0 up to 399 rather than 1 to 400.

I'm not quite sure why you'd want 100 items padding out the start of the array, but for what it's worth, here's a short way of doing what you want. It's also one of the few times the Array constructor is actually useful:

var parts = new Array(100).concat(myString.split(','));
Tim Down
+1  A: 

we can add elements at the beginning of an array by using unshift() method. Here is the general syntax for using unshift() method.

scripts.unshift("VAL01","VAL02");

Here scripts is our array object and we are adding two new elements VAL01 and VAL02 at the beginning of this array by using unshift() method.

so you can use unshift to add 100 array elements before your splitted string

I hope tht will solve your purpose

Ashutosh Singh
A: 

If you don't want 100 padding elements at the beginning (index 0 to 99), you don't want to use an array. Arrays are always continious with the indexes. So you are probably looking for an object.

var obj = {}
for ( var i = 0; i < arr.length; i++ )
{
    obj[ i + 100 ] = arr[i];
}

However you shouldn't do it like that, because using an object reduces your possibilities to work with. If you don't want to add another 100 elements at the beginning (in which case you can just add those to the beginning of the existing array), then you should rather work with the original array and simply shift the index manually when you access it.

poke
A: 

Are you sure that you need this? You could simply substract 100 from your offset to get to that value. To this, arrays in JavaScript are zero-indexed. Which means that the first item can be accessed using myString[0] rather than myString[1].

elusive
A: 

Use a function to read the offset value

function getOffSetValue(arr, index, offset)
{
    if(offset == undefined)
         offset = 100;
    return arr[index - offset];
}

var st = "val1,val2,val3,val4,val5";
var a = st.split(',');

console.log(getOffSetValue(a, 102));
Amarghosh