【问题标题】:Javascript function returning undefined when passing key value传递键值时返回未定义的Javascript函数
【发布时间】:2018-10-28 09:39:00
【问题描述】:

Console.log 返回:

key1
未定义

我希望看到:

key1
[“第一”,“第二”]


var testfunc = function(a) {
    var matrix = {
        key1: ["first", "second"],
        key2: ["third", "fourth"]
    };

    var b = matrix.a;

    console.log(a);

    console.log(b);
}

var otherfunc = function() {
    return "key1";
}

testfunc(otherfunc());

【问题讨论】:

    标签: javascript object key parameter-passing undefined


    【解决方案1】:

    您必须使用bracket notation 来访问动态属性。

    所以应该是:matrix[a] 而不是未定义的matrix.a

    var testfunc = function(a) {
        var matrix = {
            key1: ["first", "second"],
            key2: ["third", "fourth"]
        };
    
        var b = matrix[a];
    
        console.log(a);
    
        console.log(b);
    }
    
    var otherfunc = function() {
        return "key1";
    }
    
    testfunc(otherfunc());

    const obj = {
      x: 'x',
      y: 'y'
    };
    
    const x = 'y';
    console.log(obj.x);
    console.log(obj[x]);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多