我正在使用这样的数组:
var table = [a: 'text_1', b: 'test_2'];
我需要使用单个函数或方法显示该数组的所有元素,但我们必须考虑“a”和“b”是字符或字符串,而不是数字。
这就是为什么我不能使用 array.forEach() 方法!
有什么想法吗?
最佳答案
你的数组声明看起来有点不对劲。您发布的代码出现语法错误。
<小时/>如果你希望这是一个数组,它应该看起来像这样:
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`...
}
}
您还可以使用流行的Underscore或Lodash以更漂亮的方式完成此任务的库:
_.each(table, function (value, key) {
// ...do something with `value` and `key`...
});
关于javascript - 如何在Javascript中显示带有字符索引的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34582536/