2015-07-03 35 views
0

我正在研究JavaScript挑戰,要求您編寫函數以:「返回值(第二個參數)應該返回的最低索引插入排序數組(第一個參數),例如,where([1,2,3,4], 1.5)應返回1,因爲它大於1 (0th index),但小於​​。對數組進行排序並將值插入該數組並返回最低索引的函數

提示表示在本次挑戰之前使用內置的「.sort()」方法,這是我不熟悉的方法。以下是我迄今爲止的內容,我認爲我很遙遠。

function where(arr, num) { 
    arr.push(num).sort(function(a,b){return a-b;}); 
    return arr.indexOf(num); 
} 

console.log(where([40, 60], 50)); // returns "unexpected identifier" 
+1

'push'返回該數組的新長度,而不是在陣列本身。你無法排序長度。 – Xufox

+0

我在找什麼方法將參數'num'添加到'arr'的末尾,然後讓我排序'arr'?我的「排序」方法是否正確實施排序我的數組? @Xufox –

+0

只需將兩條語句分開!首先'arr.push(num)',然後'arr.sort(...)'。是的,'sort'函數看起來沒問題。 – Xufox

回答

3

如@Xufox正確地說,push返回該數組的新長度和數組本身。

重新排序的代碼如下所示:

function where(arr, num) { 
    arr.push(num); // Carry out push operation. 
    arr.sort(function(a,b){return a-b;}); // Sort array. 
    return arr.indexOf(num); // Return index of 'num'. 
} 

console.log(where([40, 60], 50)); 
4

拆分兩個statments。

function where(arr, num) { 
 
    arr.push(num); 
 
    arr.sort(function(a, b) { 
 
    return a - b; 
 
    }); 
 
    return arr.indexOf(num); 
 
} 
 

 
console.log(where([40, 60], 30)); // 0 
 
console.log(where([40, 60], 50)); // 1 
 
console.log(where([40, 60], 70)); // 2

0
function where(arr, num) { 
    let index = arr.sort((x,y) => x-y) 
       .find(x => num <= x); 

    return index === undefined? arr.length: arr.indexOf(index); 
} 
-1
function getIndexToIns(arr, num) { 
    arr.sort(function(a, b) { 
    return a - b; 
}); 
    var i=0; 
    while(num>arr[i]) 
    i++; 
return i; 
} 
+0

這是幹什麼的? –

+0

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

相關問題