有人能帮忙解释一下为什么长度返回为0吗?非常感谢您的帮助!
var errors = [];
errors[''] = "Monday Morning slot already taken. Would you like to replace it?";
console.log(errors);
document.write(errors.length);
有人能帮忙解释一下为什么长度返回为0吗?非常感谢您的帮助!
var errors = [];
errors[''] = "Monday Morning slot already taken. Would you like to replace it?";
console.log(errors);
document.write(errors.length);
只有数字索引会影响数组的.length
属性。
其他命名属性是允许的,但它们不是 Array 对象的典型用法。通过使用 ""
,您可以在对象上创建一个非数字属性。 您可以像这样访问它:
errors[""];
但是你无法使用典型的Array方法来访问它。
对于具有名称的属性,通常会使用对象。无论哪种方式,您都可以使用Object.keys()
获取自身可枚举属性(包括数值索引)的数量。
Object.keys(errors).length;
因为这不是向数组添加项的正确方式,因为数组只接受数字键。你应该像这样添加:
errors.push("blah"); /*or*/ errors[0] = "blah";
//Now if you check the length:
errors.length; //1
另外,如果您将其用作对象,则''
也不是有效名称。
*更正:看起来您可以使用""
(空字符串)作为键。
var errormap = new Map();
errormap.set('err101', 'Description for error 101');
errormap.set('err102', 'Description for error 102');
console.log(errormap.get('err101'));
你可以通过简单地编写以下代码获取 Map 对象的长度:
console.log(errormap.size);
你的数组需要一个数字输入,而你当前使用的是空字符串作为索引,这是无效的。
你可以指定一个索引、用给定的元素初始化数组,或将该项推入数组中:
// Option 1: Specify index
var errors = [];
errors[0] = 'Monday Morning slot already taken. Would you like to replace it?';
// Options 2: Initialise the Array with values
var errors = ['Monday Morning slot already taken. Would you like to replace it?'];
// Option 3: Push the item to Array
var errors = [];
var myString = 'Monday Morning slot already taken. Would you like to replace it?';
errors.push(myString);