读取字符串数组作为属性名称?

时间:2019-02-23 20:19:01

标签: javascript

newDesign = {
    color: 'blue',
    shape: 'round'
}

oldDesign = {
    color: 'yellow',
    shape: 'triangle'
}

我想比较这两种设计以查看其字段是否更改,所以我写了这些:

fields = [ 'color', 'shape' ]
for (let field in fields) {
    if (oldDesign.field !== newDesign.field)
        console.log('changed')
}

但是,看起来我无法使用oldDesign.field读取字段的值。

有没有办法做到这一点?谢谢。

1 个答案:

答案 0 :(得分:0)

使用括号符号

var newDesign = {
    color: 'blue',
    shape: 'round'
}

var oldDesign = {
    color: 'yellow',
    shape: 'triangle'
}

var fields = [ 'color', 'shape' ];
for (let field in fields) {
    if (oldDesign[fields[field]] != newDesign[fields[field]])
        console.log('changed')
}

相关问题