gpt4 book ai didi

javascript - Alias ES6 解构

转载 作者:行者123 更新时间:2023-11-28 13:06:34 26 4
gpt4 key购买 nike

我正在为我的表单创建一个通用函数 checkField,并且我希望能够从状态(或任何 JavaScript 对象)中提取我作为参数

checkField(fieldname) {
const {
validityFieldObj,
fieldname
} = this.state

// Would be equivalent to `this.state[fieldname]`
// But I can't get fieldname from this.state destructuration,
// as it as already been delcared in the parameter.
// Any alternative to this issue?
}

最佳答案

要获取字段名称,您需要使用 destructuring with computed property name ,并将结果分配给变量:

const state = {
validityFieldObj: {},
abc: 3
};

function checkField(fieldname) {
const {
validityFieldObj,
[fieldname]: value
} = state;

console.log(value);
}

checkField('abc');

如果您需要提取属性名称fieldName,您可以使用别名:

const state = {
validityFieldObj: {},
fieldname: 'abc'
};

function checkField(fieldname) {
const {
validityFieldObj,
fieldname: nameOfField
} = state;

console.log(nameOfField);
}

checkField('abc');

关于javascript - Alias ES6 解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com