通过 [] 运算符访问 JS 对象的属性时,我看到了奇怪的行为。
我的表中有 3 列'attr1'、'attr2'、'attr3'。我的 JS 对象有一个名为 Attributes 的属性,它是一个哈希表,看起来像 {attr1: 'val', attr2: 'val', attr3: 'val'}
下面的代码工作正常
function onRowDataBound(e) {
var attributes = e.dataItem.Attributes;
var keys = {0: 'attr1', 1: 'attr2', 2: 'attr3'};
for (var key in keys) {
var keyVal = keys[key];
var attribute = attributes[keyVal];
if (attribute != undefined) {
e.row.cells[key].innerText = attribute;
}
}
}
但是,在下面的代码中,我动态构建了键对象; 属性始终未定义。
function getKeys() {
var keys = {};
$('#Equipment thead th').each(function() {
keys[this.cellIndex] = this.innerText;
});
return keys;
}
function onRowDataBound(e) {
var attributes = e.dataItem.Attributes;
var keys = getKeys();
for (var key in keys) {
var keyVal = keys[key];
var attribute = attributes[keyVal];
if (attribute != undefined) {
e.row.cells[key].innerText = attribute;
}
}
}
最佳答案
尝试 trim 该值:
$('#Equipment thead th').each(function() {
keys[this.cellIndex] = jQuery.trim(this.innerText);
});
您知道每次迭代时 keyVal
到底包含什么吗?
关于javascript - 无法使用哈希语法从 JS 对象检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393272/