如何在javascript中选择未知数字?

发布于 2024-09-24 13:51:09 字数 432 浏览 0 评论 0原文

例如我有:

array(2,1,3,4,5,6,7)

我已经知道 (2,1 ,3)

我应该如何得到 (4,5,6, 7 )如果我知道从 17 存在所有数字,并且这些数字我已经知道

所以我想要一个包含我的数字的数组还不知道。

抱歉,如果听起来很愚蠢:|

So for example I have:

array(2,1,3,4,5,6,7)

and I already know (2,1,3)

How should I get (4,5,6, 7) if I know that all numbers exists from 1 to 7 and the numbers what I already know

So I want an array with the numbers what I don't know yet.

Sorry if sounds stupid :|

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笨笨の傻瓜 2024-10-01 13:51:09

如果 A = (2, 1, 3) 且 B = (1, 2, 3, 4, 5, 6, 7)

那么你想要不常见的元素 (即,两者都不存在的元素)?您可以尝试以下操作:

//note: could be improved - wrote it quickly
function uncommon(a, b) {

    var map = {};
    var alreadyAdded = {};
    var uncommonElements = [];

    var arrays = (a.length > b.length) ? 
                     {first: b, second: a} : 
                     {first: a, second: b};

    for(var i = 0; i < arrays.first.length; i++) {
        map[arrays.first[i]] = true;
    }

    for(var i = 0; i < arrays.second.length; i++) {
        if(!map[arrays.second[i]]) {
            uncommonElements.push(arrays.second[i]);
            alreadyAdded[arrays.second[i]] = true;
        }
    }

    for(var i = 0; i < arrays.first.length; i++) {
        if(!map[arrays.second[i]] && !alreadyAdded[arrays.first[i]]) {
            uncommonElements.push(arrays.first[i]);
        }
    }

    return uncommonElements;
}

另请注意,如果您有:

A = (2, 1, 3, 9) 且 B = (1, 2, 3, 4, 5, 6, 7 ),您将得到 (2, 1, 3, 9) 即在任一元素中都找不到的元素。

If A = (2, 1, 3) and B = (1, 2, 3, 4, 5, 6, 7)

Then do you want the uncommon elements (i.e., elements not existing in either)? You can try this:

//note: could be improved - wrote it quickly
function uncommon(a, b) {

    var map = {};
    var alreadyAdded = {};
    var uncommonElements = [];

    var arrays = (a.length > b.length) ? 
                     {first: b, second: a} : 
                     {first: a, second: b};

    for(var i = 0; i < arrays.first.length; i++) {
        map[arrays.first[i]] = true;
    }

    for(var i = 0; i < arrays.second.length; i++) {
        if(!map[arrays.second[i]]) {
            uncommonElements.push(arrays.second[i]);
            alreadyAdded[arrays.second[i]] = true;
        }
    }

    for(var i = 0; i < arrays.first.length; i++) {
        if(!map[arrays.second[i]] && !alreadyAdded[arrays.first[i]]) {
            uncommonElements.push(arrays.first[i]);
        }
    }

    return uncommonElements;
}

Also note that if you had:

A = (2, 1, 3, 9) and B = (1, 2, 3, 4, 5, 6, 7), you would get (2, 1, 3, 9) i.e., elements not found in either one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文