這是一個簡單的練習,我只是為了練習和休閑而做的,我以各種方式完成了它,但我想知道是否有更實用的方法或使用 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;
}
uj5u.com熱心網友回復:
如果您對只回傳總和等于目標值的一對數字(可以說是第一個匹配項)的函式感到滿意,那么這可能就足夠了:
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;
}
uj5u.com熱心網友回復:
我使用 forEach 更改了 for 回圈(更有效)并且不需要 copyArray 陣列,因此我將其洗掉。我還用 shift() 更改了 pop(),我認為您想移動陣列而不是彈出它(如果我正確理解了任務)。
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);
return;
}
});
return newArr;
}
uj5u.com熱心網友回復:
用于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 (e.g. 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>
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363484.html
標籤:javascript 数组 表现
