简体   繁体   English

Javascript:使用非连续键迭代数组

[英]Javascript: Iterating over array with non-consecutive keys

I need to iterate over an array for which the keys are non-consecutive: 我需要迭代一个非连续键的数组:

var messages = new Array();
messages[0] = "This is the first message";
messages[3] = "This is another message";

Obviously using the index of a for loop will not work as it depends on the keys being sequential: 显然使用for循环的索引将不起作用,因为它取决于顺序的键:

for (var i=0 ; i<messages.length ; i++) {
    alert(messages[i]); // Will only alert the first message, as i is never equal to 3
}

What is the canonical way of dealing with this, seeing as the for-each syntax is not intended for iterating over values in an array in javascript ? 什么是处理这个的规范方法,因为for-each语法不是用于在javascript中迭代数组中的值 Thanks. 谢谢。

The idiomatic way would be to use an object, not an array. 惯用的方法是使用一个对象,而不是一个数组。 Just be sure to check hasOwnProperty to make sure you don't pick up stray things which may have been added to the prototype. 请务必检查hasOwnProperty以确保您不会拾取可能已添加到原型中的杂散物品。

var messages = { };
messages[0] = "This is the first message";
messages[3] = "This is another message";

for (var i in messages) {
    if (messages.hasOwnProperty(i))
        alert(messages[i]); 
}

Or, the more modern way would be to use Object.keys 或者,更现代的方式是使用Object.keys

Object.keys(messages).forEach(prop => {
    alert(messages[prop]);
});

Be sure to transpile that code with Babel if you plan on running it in older browsers like IE. 如果您计划在IE等旧版浏览器中运行它,请务必使用Babel来传输该代码。

for(var i in messages)
{
    console.log(messages[i]);
}

You could ignore the undefined properties... 你可以忽略undefined属性......

for (var i=0 ; i<messages.length ; i++) {
    if(messages[i] !== undefined)
        alert(messages[i]);
}

Or use forEach , which will ignore undefined undeclared properties... 或者使用forEach ,它将忽略undefined未声明属性...

messages.forEach(function(v,i) {
    alert(v);
});

Simple! 简单! if the array has regular gaps between the indices do this: 如果数组在索引之间有规律的间隙,请执行以下操作:

for (var i = 0 ; i < messages.length; i += gap) {
    alert(messages[i]); // Will only alert the messages at the regular interval/gap 
}

You can use each() jQuery method to do this. 您可以使用each() jQuery方法来执行此操作。

$.each(messages, function(index, val){
    alert(val); 
});

From jQuery docs 来自jQuery文档

each()

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. 通用迭代器函数,可用于无缝迭代对象和数组。 Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. 具有length属性的数组和类似数组的对象(例如函数的参数对象)由数字索引迭代,从0到length-1。 Other objects are iterated via their named properties. 其他对象通过其命名属性进行迭代。

When you create an array and give it values at 0 and 3 , undefined values are created at 1 and 2 . 创建数组并将其undefined03 ,将在12处创建undefined值。 try this: 试试这个:

$.each(messages, function(i,val) { 
  if (val) {
    alert(val);
  } 
});

For a use case such with the assumptions: 对于具有以下假设的用例:

array.length >== 1 (ie: an array with meaningful data in it already) array.length >== 1 (即:已包含有意义数据的数组)

Where you are interested in the data from array[1], array[15], array[45] etc 您对array[1], array[15], array[45]等数据感兴趣的地方

You can do something similar to: 你可以做类似的事情:

var array = ["you","will","become","strong","with","the","codes","padawan"];
var values = [1,5,7];


for (var i = 0; i < values.length; i++){
    var cypher = values[i];
    console.log(array[cypher]);
}
//will, the, padawan

Or perhaps something more meaningful such as: 或许更有意义的事情,例如:

for (var i = 0; i < values.length; i++){
    var cypher = values[i];
    aService.aFn.(array[cypher],cb);
}
//calls aService.aFn separately for each value array[1] , array[5] , array[7] passed as args

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM