本文介绍了在JavaScript的关联数组中使用整数作为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建一个新的JavaScript数组并使用整数作为键时,该数组中直到该整数为止的每个元素都会被创建为undefined.

When I create a new JavaScript array, and use an integer as a key, each element of that array up to the integer is created as undefined.

例如:

var test = new Array();
test[2300] = 'Some string';
console.log(test);

将输出2298个未定义的和一个某些字符串".

will output 2298 undefined's and one 'Some string'.

我应该如何让JavaScript使用2300作为字符串而不是整数,或者应该如何避免实例化2299空索引?

How should I get JavaScript to use 2300 as a string instead of an integer, or how should I keep it from instantiating 2299 empty indices?

推荐答案

使用对象.但是,请注意,您可以具有整数键. JavaScript将将整数转换为字符串.以下输出20,不是未定义的:

Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:

var test = {}
test[2300] = 20;
console.log(test["2300"]);

这篇关于在JavaScript的关联数组中使用整数作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:49
查看更多