数组中的优化对,对的总和是JavaScript中的随机值

时间:2017-01-06 11:53:25

标签: javascript arrays

我尝试下面的代码用于从数组中打印对,对和是随机值。但在JS中还有其他优化方法吗?

var array = [1,24,10,12,11,13,23,9,15];r 

var value = 24;

function myMthod(array,value){

       var a;
       var b;

    for (var i=0; i < array.length; i++) {

        a = array[i];

        for (var j=0; j < array.length; j++) {

            b = array[j]

            if ( (parseInt(a) + parseInt(b)) === value && result.indexOf(a+","+b) == -1 && result.indexOf(b+","+a ) == -1 ) {
               result.push( a+","+b )
            }

        }    
    }

return result

};
myMthod(array,value);

有没有办法提供优化?提前谢谢!

2 个答案:

答案 0 :(得分:0)

首先,您需要使代码正常工作。您需要将100更改为value

if ( (parseInt(a) + parseInt(b)) === value && result.indexOf(a+","+b) == -1 && result.indexOf(b+","+a ) == -1 ) {
//                                   ^^^^^

最好将其更改为没有parseInt的版本,因为您使用数字。

if (a + b === value && result.indexOf(a + "," + b) == -1 && result.indexOf(b + "," + a) == -1) {
//  ^^^^^

&#13;
&#13;
var array = [1, 24, 10, 12, 11, 13, 23, 9, 15];
var value = 24;

function myMthod(array, value) {
    var a, b, result = [];

    for (var i = 0; i < array.length; i++) {
        a = array[i];
        for (var j = 0; j < array.length; j++) {
            b = array[j];
            if (a + b === value && result.indexOf(a + "," + b) == -1 && result.indexOf(b + "," + a) == -1) {
                result.push(a + "," + b)
            }
        }
    }
    return result;
}

console.log(myMthod(array, value));
&#13;
&#13;
&#13;

稍快的版本可以忽略已经循环的项目,并且无需检查插入的项目即可工作。

&#13;
&#13;
var array = [1, 24, 10, 12, 11, 13, 23, 9, 15];
var value = 24;

function myMthod(array, value) {
    var a, b, i, j, result = [];

    for (i = 0; i < array.length - 1; i++) {
        a = array[i];
        for (j = i + 1; j < array.length; j++) {
            b = array[j];
            if (a + b === value) {
                result.push([a, b]);
            }
        }
    }
    return result;
}

console.log(myMthod(array, value));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

没有必要使用第二个循环,当你得到一个项目时,只需检查数组中是否有value - item

function pairs(array, value) {
    var rs = [];

    array.forEach(function(item, index) {
        if (array.includes(value - item, index))
            rs.push([item, value - item]);
    });

    return rs;
}

var array = [1,24,10,12,11,13,23,9,15];
var value = 24;


console.log(pairs(array, value))