在 Javascript 中调用或访问嵌套的 const inside 变量
Call or access nested const inside variable in Javascript
我是 javascript 的新手,但我需要帮助,我可以从 const 块内的变量外部访问或调用吗? ,从底部的代码,我需要访问变量在 addAttributes 块内的 layerAttributes,我尝试 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);
};
据我了解,您希望能够从块外部访问 layerAttributes,您可以在外部声明它,然后在 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
告诉我这是不是你的意思
我是 javascript 的新手,但我需要帮助,我可以从 const 块内的变量外部访问或调用吗? ,从底部的代码,我需要访问变量在 addAttributes 块内的 layerAttributes,我尝试 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);
};
据我了解,您希望能够从块外部访问 layerAttributes,您可以在外部声明它,然后在 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
告诉我这是不是你的意思