【问题标题】:PHP variable property in javascriptjavascript中的PHP变量属性
【发布时间】:2020-01-19 13:39:58
【问题描述】:

在 PHP 中通常使用可变变量,例如

foreach(['key1', 'key2', 'key3'] as $key) {
    if (!$object->$key)
        $object->$key = 'add some values';
}

我想知道如何在 javascript 中做到这一点?

实际用例:

我们有多个必需的输入字段(例如:namesurnameemail)在带有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.';
});

【问题讨论】:

标签: javascript php arrays object variables


【解决方案1】:

你可以做到这一点,几乎与 php 中的方式相同:

class Person {

  constructor(name, surname, email) {
    this.name = name;
    this.surname = surname;
    this.email = email;
    this.errors = {}
  }
  
  validate () {
    ['name', 'surname', 'email'].forEach((field) => {
      if (!this[field])
          this.errors[field] = field + ' is required.';
    });
  }
  
  getErrors() {
    return this.errors;
  }
}

let s = new Person('john','doe');
s.validate();
console.log(s.getErrors());

【讨论】:

    猜你喜欢
    • 2014-03-05
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多