【问题标题】:How to access the name of an array / object, not the values? [duplicate]如何访问数组/对象的名称,而不是值? [复制]
【发布时间】:2015-10-13 03:43:57
【问题描述】:

我已经重写了以下每个版本。在我的输出中,我希望它记录

[['motorbike', 0, vehicles],[['car', 1, vehicles]],[['plane', 2, vehicles]]]

但是,它目前记录了数组的全部内容,而不仅仅是标题。我怎样才能让它提供列表名称?

function each(collection, callback) {
    if (Array.isArray(collection)) {
        for (var i = 0; i < collection.length; i++) {
            callback(collection[i], i, collection);
        }
    } else {
        return collection;
    }
}
var vehicles = ['motorbike', 'car', 'plane'];
var iterationInputs = [];
each(vehicles, function(vehicle, index, list) {
    iterationInputs.push([vehicle, index, list]);
});

console.log(iterationInputs);

【问题讨论】:

  • 没有“列表名称”.....你想要一个对象而不是一个数组吗?也许我不知道你在问什么……你希望日志是什么样的?>
  • 我希望它注销[['motorbike', 0, vehicles],[['car', 1, vehicles]],[['plane', 2, vehicles]]],但它正在注销[["motorbike", 0, ["motorbike", "car", "plane"]],["car", 1, ["motorbike", "car", "plane"],["plane", 3, ["motorbike", "car", "plane"]

标签: javascript arrays foreach each


【解决方案1】:

你不能访问变量名 我认为你需要使用哈希表,这个链接可以帮助你http://www.mojavelinux.com/articles/javascript_hashes.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    相关资源
    最近更新 更多