【问题标题】:How to display the elements of an array with character index in Javascript?如何在Javascript中显示具有字符索引的数组元素?
【发布时间】:2016-01-03 22:48:40
【问题描述】:

我正在使用这样一个数组:

var table = [a: 'text_1', b: 'test_2'];

我需要用一个函数或方法显示这个数组的所有元素,但我们必须考虑到 'a' 和 'b' 是字符或字符串,而不是数字。

这就是为什么我不能使用 array.forEach() 方法!

有什么想法吗?

【问题讨论】:

  • 那是无效的,至少几乎可以,但是数组应该有编号的索引,对象应该有键
  • Array 类似于['a','b'],但在您的情况下,您的变量是写得不好的对象,您应该改用var table = {a: 'text_1', b: 'test_2'}
  • 如果它是一个对象,你只需做for (var key in table) { ...
  • 谢谢大家,我会用对象的!

标签: javascript arrays


【解决方案1】:

你的数组声明看起来有点不对劲。您发布的代码给出了语法错误。


如果你希望它是一个数组,它应该看起来像这样:

var table = ['text_1', 'test_2'];

您应该可以使用forEach 进行迭代:

table.forEach(function (entry) {
  // 'text_1', then 'test_2', etc...
});

如果你希望它是一个带有字符串键的对象,它应该看起来像这样:

var table = {a: 'text_1', b: 'test_2'};

你可以这样迭代:

// For every key in `table`...
var value;
for (var key in table) {

  // If the table has the key (and it isn't somewhere higher
  // up in the prototype chain...
  if (table.hasOwnProperty(key)) {
    value = table[key];

    // ...do something with `value`...
  }
}

您还可以使用流行的 UnderscoreLodash 库以更漂亮的方式完成此操作:

_.each(table, function (value, key) {
  // ...do something with `value` and `key`...
});

【讨论】:

  • 感谢@Evan 这么长的回答,我学到了很多东西。
【解决方案2】:

你想要更像这样的东西:

var table = {a: 'text_1', b: 'test_2'};
for(key in table){
    console.log(key); //logs a and b
    console.log(table[key]); //logs 'text_1' and 'test_2'
}

您的表格是一个对象,而不是一个数组。

【讨论】:

  • 谢谢@JeremyJackson,我会使用一个对象!
【解决方案3】:

你想要的数据结构是一个普通的对象:

var table = {a: 'text_1', b: 'test_2'};

您可以使用普通的对象迭代器循环 (for...in),或者如果您想访问所有 Array 方法,您可以遍历对象键(例如,如果您想过滤):

Object.keys(table).filter(function(key) {
  console.log(table[key]);

  return table[key] !== 'text_1';
});

【讨论】:

  • 谢谢乔希的回答,我会试试你给我的这个过滤方法!
  • @TimothePearce filter 与此无关,我只是展示了一个在普通对象结构上使用本机 Array 方法的示例
  • 是的,我明白了,它就像一个魅力,谢谢;)
猜你喜欢
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多