gpt4 book ai didi

javascript - 如何为for循环赋值

转载 作者:行者123 更新时间:2023-12-03 02:01:33 28 4
gpt4 key购买 nike

我正在尝试为对编程一无所知的用户创建一个界面。所以我希望他们添加一些东西,然后他们可以复制粘贴代码,这一切都必须起作用。

所以我有一个如下所示的配置对象:

var initSocialShare = {
config: {
facebook: false,
linkedin: false,
twitter: false,
pocket: false,
copy: false
}
}

而且我想将其渲染在这样的文本区域内:

document.querySelector('#shareButton-code').innerHTML += 
`<script>
var initSocialShare = {
config: {
facebook: ${obj},
linkedin: ${obj},
twitter: ${obj},
pocket: ${obj},
copy: ${obj}
}
}
${initButtons}
${showOverlay}
${copyText}
initButtons()
</script>`;

如何在脚本中呈现 for 循环的结果:

for (var key in initSocialShare.config) {
// if (!initSocialShare.config.hasOwnProperty(key)) continue;

var obj = initSocialShare.config[key];
console.log(obj);
}

这是在我的 init 方法中,我将链接推送到数组:

 if(initSocialShare.config.facebook){
s.push( '"#" id="fs_facebook-btn" data-count="fb" onclick="window.open(\'https://www.facebook.com/sharer/sharer.php?u=' + u + "', '_blank', 'scrollbars=0, resizable=1, menubar=0, left=100, top=100, width=550, height=440, toolbar=0, status=0');return false\" title=\"Share on Facebook\"")
}

因此,当用户复制上面的代码时,这段代码必须起作用

最佳答案

您可以像这样使用标记模板来循环模板中的替换。

document.querySelector('#shareButton-code').innerHTML +=
foo`<script>
var initSocialShare = {
config: {
facebook: ${initSocialShare},
linkedin: ${initSocialShare},
twitter: ${initSocialShare},
pocket: ${initSocialShare},
copy: ${initSocialShare}
}
}
</script>`;

function foo(literals, ...substitutions) {
let result = '';
let i = 0;

for (const key in initSocialShare.config) {
result += literals[i];
result += initSocialShare.config[key];
i++;
}

result += literals[literals.length - 1];
return result;
}

编辑:(现在包括所有替换)

var initSocialShare = {
config: {
facebook: false,
linkedin: false,
twitter: false,
pocket: false,
copy: false
}
}

const initButtons = 'foo';
const showOverlay = 'bar';
const copyText = 'baz';

document.querySelector('#shareButton-code').innerHTML +=
foo`<script>
var initSocialShare = {
config: {
facebook: ${initSocialShare},
linkedin: ${initSocialShare},
twitter: ${initSocialShare},
pocket: ${initSocialShare},
copy: ${initSocialShare}
}
}
${initButtons}
${showOverlay}
${copyText}
initButtons()
</script>`;

function foo(literals, ...substitutions) {
let result = '';
let i = 0;

for (const key in initSocialShare.config) {
result += literals[i];
result += initSocialShare.config[key];
i++;
}

for (let j = i; j < substitutions.length; j++) {
result += literals[j];
result += substitutions[j];
}

result += literals[literals.length - 1];
return result;
}

关于javascript - 如何为for循环赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49996261/

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