循环似乎结束了,即使期望是重置

Loop appears to end, even though expectation is to reset

我有一个对象:

var $neutrals = [
    {label : "Neutrals 1", value : "#ffffff", type : "color"},
    {label : "Neutrals 2", value : "#f8f8f8", type : "color"},
    {label : "Neutrals 3", value : "#d9d9d9", type : "color"},
    {label : "Neutrals 4", value : "#b2b3b7", type : "color"},
    {label : "Neutrals 5", value : "#5b5e65", type : "color"},
    {label : "Neutrals 6", value : "#151618", type : "color"}
];

在此对象中,我希望循环遍历每个元素,然后将每种颜色相互比较,以确保该对通过特定的亮度级别。这是我的代码:

function create_colors(){
    var neutral_set = $("<div/>").addClass("color-set");
    $(".color-container").html(neutral_set);
    neutral_set.append("<h3>Neutrals</h3>");

    $.each($neutrals, function(){
        var parent_color = this.value;

        var colorstrip = $("<div/>").addClass("color-strip").attr("style", "background-color:"+parent_color+";");

        neutral_set.append(colorstrip);

        $.each($neutrals, function(){
            var overlay = hexToRgb(this.value);
            var base = hexToRgb(parent_color)

            var diff_contrast = contrast(base, overlay);
            console.log(this.value+", "+parent_color);

            if(diff_contrast > 4.5)
            {
                colorstrip.append("<span style='color:"+this.value+"'>"+this.label+", "+diff_contrast+"</span>");
                return false;
            }
        })
    });
}

输出如下所示:

这接近我的预期,所有较浅的颜色都显示最低的对比度,以通过 4.5:1 的对比度,而较深的灰色和黑色是空的,没有显示,根据我的经验,白色#ffffff。是不是我用 return false 停止了循环,从而停止了循环继续?我不完全确定我在这里做错了什么。

Jspcal 的评论是正确的。最后两次迭代从未满足条件,因此永远不会附加跨度。

我猜您不会在 contrast 函数中补偿逆参数。例如:

contrast([255,255,255], [101,94,91]) //Gives 6.493852249020362
contrast([101,94,91], [255,255,255]) //Gives 0.1539918004988266

尝试修改 contrast 函数以允许这种情况:

function contrast(rgb1, rgb2) { 
    var result = (luminanace(rgb1.r, rgb1.g, rgb1.b) + 0.05) /
                 (luminanace(rgb2.r, rgb2.g, rgb2.b) + 0.05);

    if (result < 1) result = 1/result;
    return result;
}

Here's a jsFiddle of this solution.