簡體   English   中英

有沒有辦法讓這個 Javascript 代碼更高效?

[英]Is there a way to make this Javascript code more efficient?

這是一個簡單的練習,我只是為了練習和休閑而做的,我以各種方式完成了它,但我想知道是否有更實用的方法或使用 JavaScript 的許多方法來減少代碼行數。

該練習是關於接收一個數組 (arr) 和一個數字 (target) 並返回另一個數組,其中包含在“arr”中找到的一對數字,其總和等於“target”。

function targetSum3(arr, target) {
            let newArr = [];
            let copyArray = arr;
            for (let i of copyArray) {
                let x = Math.abs(i - target);
                copyArray.pop(copyArray[i]);
                if (copyArray.includes(x) && (copyArray.indexOf(x) != copyArray.indexOf(i))) {
                    newArr.push(i);
                    newArr.push(x);
                    return newArr;

                }
            }
            return newArr;
        }

如果您對 function 感到滿意,它只返回一對數字(可以說是第一個匹配項),其總和等於目標值,這可能就足夠了:

function sumPair (arr, target) {
    while(arr.length) {
        let sum1 = arr.shift();
        let sum2 = arr.find(val => sum1 + val === target);
        if (sum2) return [sum2, sum1];
    }
    return null;
}

我用 forEach 更改了 for 循環(更有效)並且不需要 copyArray 數組,所以我刪除了它。 我還用 shift() 更改了 pop(),我認為您想要移動數組而不是 pop-it(如果我正確理解了任務)。

function targetSum3(arr, target) {
        let newArr = [];
        arr.forEach(element => {
            let x = Math.abs(element - target); // calc x
            arr.shift(); // removes first element from arr (current element)
            if (arr.includes(x) && (arr.indexOf(x) != arr.indexOf(element))) {
                newArr.push(element);
                newArr.push(x);
                break;
            }
        });

    return newArr;
}

使用Array.filter查找給定數組中所有值的目標總和。 請參閱片段中的評論。

 sumsForTargetInArray(); document.addEventListener(`click`, evt => evt.target.id === `redo` && sumsForTargetInArray()); function sumsInArray(arr, target) { // clone the array const clone = arr.slice(); let result = []; while (clone.length) { // retrieve the current value (shifting it from the clone) const current = clone.shift(); // filter arr: all values where value + sum = target const isTarget = arr.filter(v => current + v === target); // add to result. // Sorting is to prevent duplicates later if (isTarget.length) { result = [...result, ...isTarget.map(v => [current, v].sort())]; } } // weed out duplicates (eg 0 + 3, 3 + 0) const unique = new Set(); result.forEach(r => unique.add(`${r[0]},${r[1]}`)); // return array of array(2) return [...unique].map(v => v.split(`,`).map(Number)); } function sumsForTargetInArray() { const testArr = [...Array(20)].map((_, i) => i); const target = Math.floor(Math.random() * 30); document.querySelector(`pre`).textContent = `testArray: ${ JSON.stringify(testArr)}\ntarget: ${target}\nResult: ${ JSON.stringify(sumsInArray(testArr, target))}`; }
 <pre></pre> <button id="redo">Again</button>

const targetSum = (arr, target) => {
    const first = arr.find((v,i,a) => arr.includes(target-v) && (arr.indexOf(target-v) !== i));
    return first ? [first, target - first] : null;
};
    
const values = [1,2,3,4,5,6,7,8,9];
console.log(targetSum(values, 1)); // null
console.log(targetSum(values, 2)); // null
console.log(targetSum(values, 3)); // [1, 2]
console.log(targetSum(values, 15)); // [6, 9]
console.log(targetSum(values, 20)); // null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM