例如,我有一个简单的for循环,该循环遍历列表并找到名为amount的属性。
lst.forEach(function (d) {
if(d.amount){} else {d.amount = 0};
});
我不想真正地重新定义实际数据或添加其他数据。我只想将其称为“ x”,但实际上将其称为“金额”。换句话说,我想用不同的本地名称来指代“金额”。
例如,
x = amount #I'm telling the computer "Hey comp, when I type x, I actually mean amount"
lst.forEach(function (d) {
if(d.x){} else {d.x = 0};
});
结果,这将产生相同的数量。
这可能吗?
最佳答案
JavaScript是一种动态语言,您可以在其中按名称引用属性。您想要使用bracket notation访问您的媒体资源:
变种
var x = "amount"
lst.forEach(function (d) {
if(d[x]){} else {d[x] = 0};
});