简体   繁体   English

为什么返回未定义?

[英]Why is it returning undefined?

I want to store as the following method, and get the constant value, by querying using key to find value or by value to find the key 我想存储为以下方法,并通过使用key查找值或按value查找键来获取常量值

function my_reference() {
  return {
    30:'',
    31:'ERR591',
    32:'ERR761',
    33:'ERR671',
    34:'ERR551',

  };
}

console.log( my_reference[31], 
             my_reference.31, 
             my_reference().31,
             my_reference()[31]
);
 my_reference[31], 

Trying to read a property (which doesn't exist) of a function. 尝试读取函数的属性(不存在)。 The property is on the object that is the return value of calling the function. 该属性位于对象上,该对象是调用函数的返回值。

 my_reference.31, 

Trying to use a number as an identifier. 尝试使用数字作为标识符。 This isn't allowed. 这是不允许的。

 my_reference().31, 

Trying to use a number as an identifier. 尝试使用数字作为标识符。 This isn't allowed. 这是不允许的。

 my_reference()[31] 

This works 这有效

You have to call function if you want it to return result, function called by : 如果要返回结果,则必须调用function,该函数由调用:

my_reference()

So the both first lines will not work because my_reference will return the function it self and not call it : 所以前两行都不起作用,因为my_reference会自行返回该函数,而不是调用它:

my_reference[31]
my_reference.31

The third also will not work console.log(my_reference().31); 第三个也无法正常工作console.log(my_reference().31); because attribute can't be numeric. 因为属性不能为数字。

Hope this helps. 希望这可以帮助。

您需要使用my_reference()执行该函数, my_reference()访问您想要的属性。.但是javascript对象中的键始终是字符串:

console.log(my_reference()['31']);

You don't need to use a function to store the references: 您不需要使用函数来存储引用:

var reference = {
    30:'',
    31:'ERR591',
    32:'ERR761',
    33:'ERR671',
    34:''
};

console.log(reference[31]);

Here is the fixed code 这是固定代码

function my_reference() {
  return {
    _30:'',
    _31:'ERR591',
    _32:'ERR761',
    _33:'ERR671',
    _34:'ERR551'
  };
}

var f = my_reference();

console.log(f["_31"]); 
console.log(f._31);
console.log(my_reference()._31);
console.log(my_reference()["_31"]); 

Variables can't be named with just numbers The first two should be the returned object 变量不能仅用数字命名前两个应该是返回的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM