开发者

JavaScript Split, change parts number

I have a dynamically generated large string which 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 v开发者_运维知识库al1
myString[102] // gives val2
myString[103] // gives val3
.
.
.
myString[500] // gives val400


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(','));


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

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 the unshift() method.

So you can use unshift to add 100 array elements before your split string.


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.


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].


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜