I'm using AJAX to send data to a controller and retrieve it. When I have console.log(result.ans2.pass)
it works.
However with console.log(result.ans + x + .pass)
It keeps given me an error:
expected expression, got '.'
$.ajax({ type: "POST", url: 'http://some-url', dataType: "json", data: { datasent: dataKey }, cache: false, success: function(result) { var x = 2; console.log(result.ans + x + .pass) } });
要使用字符串访问对象的属性,您需要使用方括号表示法:
console.log(result['ans' + x].pass)
You can't dynamically add to a variable name like you're trying to do with dot notation . Instead, you can use bracket notation and concatenation so that you can access your property name using a string:
console.log(result["ans"+x].pass)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.