简体   繁体   English

JS-从对象提取Array属性

[英]JS - extract an Array property from an object

Code: 码:

var obj = {val1: 'Test',val2: 'Test','array[]': [ '1', '1', '1', '1', '1', '1', '1', '1', '1', '1' ] };

console.log(obj.array);

Issue: the above console.log returns undefined. 问题:上面的console.log返回未定义。 For many, it might be obvious, but I'm a newb and trying to figure out how to log the array[] (it works if the property is simply defined as {'array': ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]}). 对于许多人来说,这也许很明显,但是我是个新手,试图弄清楚如何记录array [](如果将属性简单定义为{'array':[“ 1”,“ 1”, “ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”]})。

Expected output: ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"] 预期输出:[“ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”,“ 1”]

Like this: 像这样:

console.log(obj['array[]']);

The property you are trying to access is called array[] , not array . 您尝试访问的属性称为array[] ,而不是array

You'll have to use square bracket notation to access the property (ie obj['array[]'] and not obj.array[] ) because the property name is not a valid JavaScript identifier, ie a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. 您必须使用方括号符号来访问属性(即obj['array[]']而不是obj.array[] ),因为属性名称不是有效的JavaScript标识符,即也包括字母数字字符序列包括不能以数字开头的下划线(“ _”)和美元符号(“ $”)。

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors 参考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_Accessors

the object property is named array[] , not array . 对象属性命名为array[] ,而不是array Rename it to array and you will get the results you are expecting. 将其重命名为array ,您将获得预期的结果。

 var obj = {val1: 'Test',val2: 'Test','array': [ '1', '1', '1', '1', '1', '1', '1', '1', '1', '1' ] }; console.log(obj.array); 

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

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