This question already has an answer here:
这个问题在这里已有答案:
- Convert JavaScript string in dot notation into an object reference 24 answers
将点符号中的JavaScript字符串转换为对象引用24个答案
I have the following Javascript variable:
我有以下Javascript变量:
scope.model = {
errors: {
email: ["error1", "error2"],
name: ["error"]
}
}
And I have a function as follows:
我有如下功能:
function (scope, element, attributes) {
if (scope.model.errors) {
if (scope.model.errors[attributes.validator])
// Do something
}
The problem is that the errors are not always on the same scope variable.
问题是错误并不总是在同一范围变量上。
I can have something like:
我可以有类似的东西:
scope.view = {
newErrors: {
email: ["error1", "error2"],
name: ["error"]
}
Inside the function I know how to get the variable where they are:
在函数内部,我知道如何获取它们所在的变量:
function (scope, element, attributes) {
var errors = attributes["validatorErrors"];
// Note: errors is this case "view.newErrors"
// So the following code would become:
if (scope.view.newErrors) {
if (scope.view.newErrors[attributes.validator])
// Do something
}
UPDATE
I have tried [] before but now I understand why it was not working:
我之前尝试过[],但现在我明白为什么它不起作用了:
function (scope, element, attributes) {
var errors = attributes["validatorErrors"];
if (scope[errors]) {
if (scope.[errors][attributes.validator])
// Do something
}
If errors = 'errors' it will work ...
如果错误='错误',它将起作用......
If errors = 'model.errors' it won't. In this case I would need:
如果errors ='model.errors'则不会。在这种情况下,我需要:
scope['model']['errors'] ...
How can I solve this?
我怎么解决这个问题?
2 个解决方案
#1
Use the array notation:
使用数组表示法:
if (scope[errors]) {
if (scope[errors][attributes.validator]) {
// do something
#2
You actually already know the answer because youre using it in your example.
你实际上已经知道了答案,因为你在你的例子中使用它。
scope[newErrors][attributes.validators]
Just be careful here because it will break when scope[newErrors] is undefined. So some error handling might be needed
这里要小心,因为当scope [newErrors]未定义时它会中断。因此可能需要一些错误处理
#1
Use the array notation:
使用数组表示法:
if (scope[errors]) {
if (scope[errors][attributes.validator]) {
// do something
#2
You actually already know the answer because youre using it in your example.
你实际上已经知道了答案,因为你在你的例子中使用它。
scope[newErrors][attributes.validators]
Just be careful here because it will break when scope[newErrors] is undefined. So some error handling might be needed
这里要小心,因为当scope [newErrors]未定义时它会中断。因此可能需要一些错误处理