如何在 JavaScript 中创建一个索引从 1 开始的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2826682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an array in JavaScript whose indexing starts at 1?
提问by detj
By default the indexing of every JavaScript array starts from 0. I want to create an array whose indexing starts from 1 instead.
默认情况下,每个 JavaScript 数组的索引从 0 开始。我想创建一个索引从 1 开始的数组。
I know, must be very trivial... Thanks for your help.
我知道,一定很琐碎……谢谢你的帮助。
回答by cletus
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.
这不是微不足道的。不可能。您能做的最好的事情是使用从 1 开始的数字属性创建一个对象,但这不是一回事。
Why exactly do you want it to start at 1? Either:
为什么你希望它从 1 开始?任何一个:
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).
从 0 开始并根据需要调整您的指数;或者
从 0 开始,忽略索引 0(即只使用索引 1 及以上)。
回答by Maurice Schleu?inger
Since this question also pops up for a Google search like "javascript start array at 1" I will give a different answer:
由于这个问题也会在 Google 搜索中弹出,例如“javascript start array at 1”,我将给出不同的答案:
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
来源:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
回答by Gras Double
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)
请注意,这些键实际上不是整数,对象键始终是字符串。
此外,我们不能使用点表示法进行访问。(MDN - 属性访问器)
I'd choose the first solution, which I think is less confusing.
我会选择第一个解决方案,我认为它不那么令人困惑。
回答by leonheess
You could use deleteto remove the first element like so:
您可以使用delete删除第一个元素,如下所示:
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:
如果您想确保始终获得第一个真实元素而不管索引如何并且可以访问 ES6,您可以使用:
arr.find(e => e)
回答by asiniy
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?
好的,根据@cletus 的说法,你不能这样做,因为它是一个内置的 javascript 功能,但如果你仍然想要它,你可以采用稍微不同的方式。您可以编写自己的 Array 的索引相关函数(如reduce, map, forEach)以从 1 开始。这不是一项艰巨的任务,但仍然要问自己:我为什么需要它?
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"]
回答by RAM
First add this function to your javascript codes:
首先将此函数添加到您的 javascript 代码中:
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
观看现场演示
回答by Lucas Bustamante
I faced a situation where I neeeded the array to start from index 1. Here's what I did:
我遇到了需要数组从索引 1 开始的情况。这就是我所做的:
var products = ['bar', 'baz'];
products = $.makeArray(products); // necessary to unshift a jQuery object
products.unshift('foo'); // add "foo" to the beginning of the array
$(products).each(function(index) {
if (index === 0) {
return true; // we will skip "foo"
}
// From now on we can use products[index] starting from 1
});
回答by wle8300
Simple, just make two changes to the classic Javascript forloop.
很简单,只需对经典的 Javascriptfor循环进行两处更改。
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);
}

