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

发布于 2024-12-31 22:06:27 字数 523 浏览 0 评论 0原文

我需要迭代一个键不连续的数组:

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

显然使用 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
}

处理此问题的规范方法是什么,如 for-each 语法不适用于在 javascript 中迭代数组中的值?谢谢。

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 (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? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

彩扇题诗 2025-01-07 22:06:27

惯用的方法是使用对象,而不是数组。请务必检查 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]); 
}

或者,更现代的方法是使用 Object.keys

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

如果您计划在 IE 等旧版浏览器中运行该代码,请务必使用 Babel 转译该代码。

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.

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(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.

万劫不复 2025-01-07 22:06:27
for(var i in messages)
{
    console.log(messages[i]);
}
for(var i in messages)
{
    console.log(messages[i]);
}
冷血 2025-01-07 22:06:27

您可以忽略 undefined 属性...

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

或者使用 forEach,它将忽略 undefined 未声明的属性...

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

You could ignore the undefined properties...

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

Or use forEach, which will ignore undefined undeclared properties...

messages.forEach(function(v,i) {
    alert(v);
});
自在安然 2025-01-07 22:06:27

简单的!如果数组的索引之间有规则的间隙,请执行以下操作:

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

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 
}
昵称有卵用 2025-01-07 22:06:27

您可以使用 each() jQuery 方法来执行此操作。

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

来自 jQuery 文档

each()

通用迭代器函数,可用于无缝迭代
在对象和数组上。数组和类数组对象
length 属性(例如函数的参数对象)被迭代
按数字索引,从 0 到 length-1。其他对象通过迭代
他们的命名属性。

You can use each() jQuery method to do this.

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

From jQuery docs

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. Other objects are iterated via
their named properties.

堇年纸鸢 2025-01-07 22:06:27

当您创建数组并在 03 处为其指定值时,会在 11 处创建 undefined 值。代码>2。试试这个:

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

When you create an array and give it values at 0 and 3, undefined values are created at 1 and 2. try this:

$.each(messages, function(i,val) { 
  if (val) {
    alert(val);
  } 
});
你爱我像她 2025-01-07 22:06:27

对于假设如下的用例:

array.length >== 1
(即:其中已经包含有意义数据的数组)

如果您对 array[1]、array[15]、array[45] 等中的数据感兴趣,

您可以执行类似以下操作:

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

或者也许是更有意义的事情,例如:

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

For a use case such with the assumptions:

array.length >== 1
(i.e: an array with meaningful data in it already)

Where you are interested in the data from array[1], array[15], array[45] etc

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文