我尝试在我的网站上实现某种A / B,然后从不同的JSON文件中呈现响应。一个人给了我这样的回应:
variants: [
{"1": "test"},
{"2": "test_test"},
{"3": "test_test_test"}
],
winner: "1"
现在我尝试实现的是,如果设置了winner
,我想将其显示给x%的用户。
逻辑是这样的:
if (winner && winner !== "") {
var len = variants.length; // 100%
// display winner to 98% of users
// and each other variant gets 1% visibility
} else {
// do sth.
}
因此,我们的值为100%(=所有变体的长度),并希望每个non-winner
1%的可见度。 winner
将获得100% - (1%* non-winners.length
) - 就像这样。
有没有办法正确计算?
答案 0 :(得分:0)
我不确定可见度,但您可以使用opacity
给出一个值,与获胜者/其他人数一致。
function setOpacity() {
var other = document.getElementsByClassName('other');
if (data.winner && data.winner !== "") {
document.getElementById('winner').style.opacity = 1 - data.variants.length / 100;
data.variants.forEach(function (_, i) {
other[i].style.opacity = 0.01;
});
} else {
document.getElementById('winner').style.opacity = 0.01;
data.variants.every(function (_, i, a) {
other[i].style.opacity = 0.99 / a.length;
return other[i + 1];
});
}
}
var data = { variants: [{ 1: "test"}, { 2: "test_test"}, { 3: "test_test_test"}], winner: "1" };
setOpacity();
setTimeout(function () {
data.winner = '';
setOpacity();
}, 2000);

#winner { background-color: #bb0000; opacity: 0; }
.other { background-color: #bb0000; opacity: 0; }

<p id="winner">winner</p>
<p class="other">other</p>
<p class="other">other</p>
<p class="other">other</p>
&#13;
答案 1 :(得分:0)
如果我理解正确,您可以使用它来计算百分比值:
var visibilities = [];
for (var i = 0, len = variants.length; i < len; i++) {
var visibility = {};
for (var id in variants[i]) {
if (winner == id) {
visibility[id] = 1 - ((variants.length - 1) * 0.01);
}
else {
visibility[id] = .01;
}
}
visibilities.push(visibility);
}
这可以节省额外数组的可见性。现在,如果遍历变体,您可以检查可见性。希望我能帮到你。