【发布时间】:2018-11-14 04:50:20
【问题描述】:
我在尝试访问存储在数组中的对象的各个字段时遇到了问题。
我有一个非统一对象数组,我们将调用 cache。
var cache = new Array();
put 函数允许将项目添加到数组中。
function put(item, value) {
cache[item] = value;
}
使用示例:
var item_abc = { item_a: 'some value', item_b: 'another value' };
put('ITEM_ABC',item_abc);
有问题的函数称为 update,它使用新的 值更新数组中 item 的 field >.
function update(item, field, value) {
cache[item][field] = value;
}
麻烦的代码如下:
update('ITEM_ABC','item_a','a new value');
在浏览器中,这似乎可以正常工作,但在“--use_strict”Node.js 环境中,它会遇到问题。我假设这与优先级以及评估多维数组与对象字段的方式有关。
当对象本身存在于数组中时,如何在不知道字段名称的情况下在运行时引用对象字段?
从相关字段读取总是返回undefined。
function check(item, field) {
console.log(cache[item][field]);
if (typeof cache[item][field] !== 'undefined')
console.log('field exists');
else
console.log('field undefined');
}
跑步:
check('ITEM_ABC','item_a');
输出:
undefined
'field undefined'
【问题讨论】:
-
您能告诉我们您在使用
use strict时遇到的错误吗? -
我在这个问题中没有看到任何 JSON。 JSON 是一种数据序列化格式。听起来您在谈论 JavaScript 对象。
-
没有错误,但
typeof cache[item][field]总是undefined -
以
var cache = {};开头(JavaScript 没有关联数组。) -
如果你使用严格模式你不能有一个名为包的变量。
标签: javascript arrays node.js javascript-objects