Javascript/Jquery使用变量访问对象
可能重复:Javascript/Jquery使用变量访问对象,javascript,jquery,arrays,object,Javascript,Jquery,Arrays,Object,可能重复: 通过ajax调用,我收到一个对象:E 此对象包含许多子元素:宽度,高度,等等 console.log(E.width)提供了E.width 分配变量时:templement='width' 为什么console.log(e.tempElement)返回“undefined”,如何通过变量访问对象的子元素 $(function () { $('#widthSelect').on('change', function () { var updateArray =
通过ajax调用,我收到一个对象:E 此对象包含许多子元素:
宽度
,高度
,等等
console.log(E.width)
提供了E.width
分配变量时:templement='width'
为什么console.log(e.tempElement)返回“undefined”,如何通过变量访问对象的子元素
$(function () {
$('#widthSelect').on('change', function () {
var updateArray = new Array();
updateArray[0] = 'height';
updateArray[1] = 'rim';
updateArray[2] = 'load';
updateArray[3] = 'speed';
updateArray[4] = 'brand';
updateArray[5] = 'season';
getValues(updateArray);
});
function getValues(updateArray) {
var data = updateArray.join('=&') + '=';
$.ajax({
type: 'POST',
dataType: 'json',
url: '******',
data: data,
success: function (e) {
element = updateArray[0];
console.log(e.element);
}
});
}
});
试试这个:
console.log( e[element] );
当您使用像e.element
这样的“点表示法”时,
后面的位按字面意思作为属性名。您的对象没有名为“element”
的属性,因此您得到了未定义的。如果使用数组样式表示法,方括号内的位将作为表达式计算,结果将用作属性名称
e.width
// is equivalent to
e["width"] // note the quotation marks
// and equivalent to
someVariable = "width";
e[someVariable]
// and also equivalent to
e[someFunction()] // assuming someFunction() returns the string "width"