开发者

How to create an array in JavaScript whose indexing starts at 1?

By default the indexing of every JavaScript array starts from 0. I want to create an array whose indexing s开发者_如何转开发tarts from 1 instead.

I know, must be very trivial... Thanks for your help.


It isn't trivial. It's impossible. The best you could do is create an object using numeric properties starting at 1 but that's not the same thing.

Why exactly do you want it to start at 1? Either:

  • Start at 0 and adjust your indices as necessary; or

  • Start at 0 and just ignore index 0 (ie only use indices 1 and up).


A simple solution is to fill the zeroth item:

var map = [null, 'January', 'February', 'March'];
'First month : ' + map[1];


Semantically it would be better to use an object:

var map = {1:'January', 2:'February', 3:'March'};
'First month : ' + map[1];

Note these keys are not ints actually, object keys are always strings.
Also, we can't use dot notation for accessing. (MDN - Property Accessors)


I'd choose the first solution, which I think is less confusing.


Since this question also pops up for a Google search like "javascript start array at 1" I will give a different answer:

Arrays can be sliced. So you can get a sliced version of the Array like this:

var someArray = [0, 1, 2, 3];

someArray.slice(1);
[1, 2, 3]

someArray.slice(2, 4);
[2, 3]

Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice


You could use delete to remove the first element like so:

let arr = ['a','b','c'];
delete arr[0];

console.log(arr[0]);
console.log(arr[1]);

Or just not define it at all:

let arr = [,'b','c'];

console.log(arr[0]);
console.log(arr[1]);

If you want to make sure that you always get the first truthy element regardless of the index and have access to ES6 you can use:

arr.find(Boolean)


The question asks "How to create an array in JavaScript whose indexing starts at 1". The accepted answer states "It isn't trivial. It's impossible."

This is true, and should be understood for good reason. However, you can create an array and omit setting the first element, in which case it will still exist (hence the accepted answer being correct) but it'll be marked as empty for you.

let usernames = ['bob', 'sally', 'frank']
let myArray = [];
let arrayIndex = 1;

usernames.map(username => {
    myArray[arrayIndex] = username;
    arrayIndex++;
})

console.log(myArray);

Array(4) [ <1 empty slot>, "bob", "sally", "frank" ]
1: "bob"
2: "sally"
3: "frank"
​length: 4

Notice that the length is "4".

console.log(myArray[0]);

undefined

Using this, there's a quirk in our favour whereby using Object.keys() on an array doesn't return empty (undefined) elements. So with the above array:

console.log(Object.keys(myArray).length);

3

Note: This is arguably a little hacky so use it with caution.

As zero of something rarely exists in our world, doing this might be useful where you are only going to access pre-defined indexes. An example would be if you have pages of a book. There isn't a page 0 as that makes no sense. And if you are always access a value directly, e.g.

const currentPage = pages[1];

Then this is fine in my opinion, as long as the code shows intent. Some will argue that ignoring a valid array index is futile, and I don't fully disagree. However, it's also futile and very annoying when I want to get page 35 of a book and the array index is 34. Meh!

When you loop your (dodgy) array with map it ignores the 0 index you didn't want:

myArray.map((value, index) => {
    console.log(index);
    console.log(value);
})

1
bob
2
sally
3
frank

For general use however, you should use index 0, so when you loop some data and spit things out you're not going to get caught out by the first one being empty.


Okay, according to @cletus you couldn't do that because it's a built-in javascript feature but you could go slightly different way if you still want that. You could write your own index-dependent functions of Array (like reduce, map, forEach) to start with 1. It's not a difficult task but still ask yourself: why do I need that?

Array.prototype.mapWithIndexOne = function(func) {
  const initial = []
  for (let i = 1; i < this.length + 1; i++) {
    initial.push(func(this[i - 1], i))
  }
  return initial
}

const array = ['First', 'Second', 'Third', 'Fourth', 'Fifth']

console.log(array.mapWithIndexOne((element, index) => `${element}-${index}`))
// => ["First-1", "Second-2", "Third-3", "Fourth-4", "Fifth-5"]

Codepen: https://codepen.io/anon/pen/rvbNZR?editors=0012


Using Array.map

[,1,2,3].map((v, i) => ++i)


Just wanted to point out that an index in c ish languages is also the offset from the first element. This allows all sorts of offset math where you don't have to subtract 1 before doing the math, only to add the 1 back later.

if you want a "1" array because the indexes are mapped to other values, that's the case for an enumeration or a hash.


First add this function to your javascript codes:

var oneArray = function(theArray)
{
    theArray.splice(0,0,null);
    return theArray
}

Now use it like this:

var myArray= oneArray(['My', 'name', 'is', 'Ram']);

alert(myArray[1]); << this line show you:   My

See live demo


Just prepend a null:

a = [1, 2, 3, 4]
a.unshift(null)
a[3]    // 3


Simple, just make two changes to the classic Javascript for loop.

var Array = ['a', 'b', 'c'];

for (var i = 1; i <= Array.length; i++) {
  //"i" starts at 1 and ends
  //after it equals "length"
  console.log(i);
}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜