【发布时间】:2020-01-19 13:39:58
【问题描述】:
在 PHP 中通常使用可变变量,例如
foreach(['key1', 'key2', 'key3'] as $key) {
if (!$object->$key)
$object->$key = 'add some values';
}
我想知道如何在 javascript 中做到这一点?
实际用例:
我们有多个必需的输入字段(例如:name、surname、email)在带有no-validate 的表单中,值会自动推送到this 实例(这意味着我们可以使用this.name 访问值、this.surname 等)。我们需要确保填写这些字段。
可以这样写:
if (!this.name)
this.errors['name'] = 'This field is required.';
if (!this.surname)
this.errors['surname'] = 'This field is required.';
if (!this.email)
this.errors['email'] = 'This field is required.';
我正在尝试提出更紧凑和准确的方法,例如:
['name', 'surname', 'email'].forEach(function (field) {
if (!this.[field])
this.errors[field] = 'This field is required.';
});
【问题讨论】:
-
您的 JS 示例中的
this是什么?即它是一个数组、一个对象还是其他东西? -
this.[field]->this[field]虽然你还需要to make sure the correct context is preserved -
另外,这些不是变量变量——在 PHP 中,变量变量是
$key = "dynamic"; $$key = "dynamically set";,其中$$key将解析为变量$dynamic -
@Taplar variable variables are a thing in PHP。看看我的另一条评论。基本上,您使用一个变量的值按名称访问另一个变量。它......非常笨拙。
标签: javascript php arrays object variables