2017-07-31 20 views
-5

我不知道Google爲此做了什麼。 我有一個數組需要添加5個數字。我想查看是否有任何元素可以乘以y來生成x。 (如果可能的話要返回的元素的索引,使if語句真)確定數組的哪個元素將使IF語句返回true J​​avascript

//所有最喜歡的「每一個」,但對單個元素

//對不起,這個垃圾措辭問題

+1

很多方法可以做到它。甚至可以在一個簡單的for()循環中完成。告訴我們你已經嘗試過什麼,並提供一個[mcve] – charlietfl

+0

也許你可以添加關於你到底想要什麼的僞代碼。你希望新元素通過什麼條件 –

+1

['some'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)? – Bergi

回答

-1

可以使用的forEach來獲取符合條件的所有元素:

let arr = [12,59,42,53,6]; 
let x = 24; 
let y = 4; 

arr.forEach(function(item, index){ 
    if(item * y === x) { 
    console.log(item, index); 
    } 
}); 
1

本來我認爲使用array.some()會有所幫助,但如下所述 - some()用於返回boolean,不應該用於返回任何其他內容。我的同事,丹工作 - 我們發現使用array.findIndex(),而不是與此幫助我們......

let input = [5, 35, 6, 7, 8]; 
 
let x = 24; 
 
let y = 4; 
 

 
let multiplies = (x, y) => number => number * y === x; 
 

 
let index = input.findIndex(multiplies(x, y)); 
 

 
console.log(index);

+0

你需要從'some'回調中返回一個布爾值。 – Bergi

+0

我明白你的意思了。編輯了我的代碼。 –

0

如果使用Array.prototype.some()函數這很簡單。

function mult(y, x) { 
    return function mult(element, index, array) { 
    return element * y === x; 
    } 
} 

[2, 5, 8, 1, 4].some(mult(10, 50)); //True since 5 * 10 = 50 
[2, 5, 8, 1, 4].some(mult(10, 100)); //False since [none of elements] * 10 = 100 

警告:上例使用closures

您可以使用上述功能通過僅提取正確的條目。 filter()

[2, 5, 8, 1, 4].filter(mult(10, 50)); //[5] 
[2, 5, 8, 1, 4].filter(mult(10, 100)); //[] 

你也可以利用上面的函數來得到哪些通過解決問題。 map()

[2, 5, 8, 1, 4].map(mult(10, 50)); //[false, true, false, false, false] 
[2, 5, 8, 1, 4].map(mult(10, 100)); //[false, false, false, false, false] 

你甚至可以把它更進一步,讓只有那些通過滿足你的標準的indicies。 reduce()

function getIndicies(a, e, i) { 
    if (e) 
     a.push(i); 
    return a; 
}; 

[2, 5, 8, 1, 4].map(mult(10, 50)).reduce(getIndicies, []); //[1] 
[2, 5, 8, 1, 4].map(mult(10, 100)).reduce(getIndicies, []); //[] 
0

一個你可以做到這一點的方法之一是寫一個返回另一個函數的一般功能,你可以用於你的計算。

multiplyByNumIsResult接受yr(您的結果)的參數,並返回接受x的另一個函數。 x是您要檢查的數組的元素。

const multiplyByNumIsResult = (y, r) => { 
    return (x) => { 
    return x * y === r; 
    } 
} 

這允許你創建基於multiplyByNumIsResult是如何被調用特定名稱的新功能。這裏有一個叫by7Is49

const by7Is49 = multiplyByNumIsResult(7, 49); 

另一個功能可能是by3Is9

const by3Is9 = multiplyByNumIsResult(3, 9); 

你基本上只是使用一般功能爲工廠作出新的定製功能。

const arr = [1, 3, 5, 7, 9]; 

如果使用map你可以返回一個新的數組,讓您檢查與功能的每個元素的結果。

const result = arr.map(by7Is49); // [ false, false, false, true, false ] 

雖然這給你一個體面的結果,它可能會更好。

如果稍微改變一般函數,可以得到一個更好的結果 - 一個只包含滿足條件的索引的數組。

const multiplyByNumIsResult = (y, r) => { 
    return (p, c, i) => { 
    if (c * y === r) p.push(i); 
    return p; 
    } 
} 

const result2 = arr2.reduce(by7Is49, []); // [ 3 ] 

DEMO

0
ArrayElem * y = x 
ArrayElem = x/y; 

所以我們實際上只需要檢查,如果這個數字(ArrayElem)是陣列英寸爲此,我們可以使用包括:

var array=[1,2,3,4], 
     x=8,y=2; 

if(array.includes(x/y)) alert("wohoo");//wohoo as 4*2=8 

獲取它的指數是一個易於:

array.indexOf(x/y) //3 as array[3] =4 

最佳(關於性能)實際上是一組:

var set = new Set(array); 
if(set.has(x/y)) alert("wohoo");