gpt4 book ai didi

javascript - 如何在js中从字符串构建变量?

转载 作者:行者123 更新时间:2023-11-30 08:18:03 25 4
gpt4 key购买 nike

我想创建一个动态函数,从字符串中返回一个变量。我正在使用 ES6 中的模板字符串,但我不知道以后如何调用它。我需要传递一个将对象作为引用的变量。

const checkDeviceWidth = type => {
if (documentWidth > 1200) return `${type}Options`;
if (documentWidth > 414) return `${type}MediumOptions`;
return `${type}MobileOptions`;
};

...

<Lottie
ref={backgroundImg}
isClickToPauseDisabled={true}
speed={1}
options={checkDeviceWidth('background')}></Lottie>

根据参数返回对象

const backgroundOptions = {
loop: true,
autoplay: true,
animationData: background.default,
};
const backgroundMediumOptions = {
loop: true,
autoplay: true,
animationData: backgroundMedium.default,
};

有了这个,我得到一个错误,在选项中我必须传递一个对象而不是一个字符串。如果没有 eval() 函数,以后如何调用它?我正在使用 React

最佳答案

你可以把你的常量放到对象中

 const myObject = {
backgroundOptions: {
loop: true,
autoplay: true,
animationData: background.default
},
backgroundMediumOptions: {
loop: true,
autoplay: true,
animationData: backgroundMedium.default
}
};

然后得到正确的属性

  const checkDeviceWidth = type => {
if (documentWidth > 1200) return myObject[`${type}Options`];
if (documentWidth > 414) return myObject[`${type}MediumOptions`];
return myObject[`${type}MobileOptions`];
};

关于javascript - 如何在js中从字符串构建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58691150/

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