调用或访问Javascript中变量内部的嵌套常量



我是javascript新手,但我需要帮助,我可以从const块内的变量外部访问或调用吗,从底部的代码中,我需要访问layerAttributes,该变量位于addAttributes块中,我尝试console.log(layerAttributes(;街区内部正在工作,但我不知道如何从街区外部调用它,非常感谢您的帮助和提前感谢。

const addAttributes = (_element) => {
let selectedElement = _element.layer;
const layerAttributes = {
trait_type: _element.layer.trait,
value: selectedElement.traitValue,
...(_element.layer.display_type !== undefined && {
display_type: _element.layer.display_type,
}),
};
console.log(layerAttributes);
if (
attributesList.some(
(attr) => attr.trait_type === layerAttributes.trait_type
)   
)
return;
attributesList.push(layerAttributes);
};

据我所知,您希望能够从块外部访问layerAttribute,您可以在外部声明它,然后在const块内部和外部使用它,如下所示:

let layerAttributes = {}; //declared outside the block

const addAttributes = (_element) => {
let selectedElement = _element.layer;
layerAttributes = { //accessed inside the block
trait_type: _element.layer.trait,
value: selectedElement.traitValue,
...(_element.layer.display_type !== undefined && {
display_type: _element.layer.display_type,
}),
};
console.log(layerAttributes);
if (
attributesList.some(
(attr) => attr.trait_type === layerAttributes.trait_type
)   
)
return;
attributesList.push(layerAttributes);

}; //end of block
console.log(layerAttributes); //accessed outside the block

告诉我这是不是你的意思

最新更新