2015-10-16 38 views
-1

我目前在下面有下面的代碼。這工作正常,但我認爲有一種更有效的方式做「轉移」和「流行」,而不是一個接一個地做。仍然理解如何工作,所以任何提示/技巧/建議,將不勝感激更有效的刪除第一個和最後一個對象的方法

我正在循環每個列表項,獲取值,然後將其添加到數組。一旦我有他們,因爲看到下面我刪除的waypts僅僅意味着是第一個和最後的點(如果可用)的第一個和最後一個值

var waypts = []; 
var inputArray = $('#enter-destinations li').each(function() { 
    var thisAddress = $(this).find('input').val(); 
    waypts.push({ location : thisAddress, stopover: true }); 
}); 

waypts.shift(); //remove first 
waypts.pop(); //remove last 
console.log(waypts); //show values that were between first and last 
+0

這實際上是這樣做的一個很好的方式,否則你就需要使用'waypts.slice創建一個新的陣列(1,-1)' – dandavis

+0

我的意思並不是要粗魯,但也許你應該問http://codereview.stackexchange.com/ –

+0

@GuiImamura沒有粗魯的,我完全不知道這可用 – RMH

回答

0

貌似popshift更快然後slice,你可以在這個jsperf看到。

slice創建一個新陣列,而popshift操作當前數組。

+0

感謝您的參考 – RMH

2

使用array#slice

waypts = waypts.slice(1, waypts.length - 1) 
+0

數組,而不是元素...... – dandavis

+0

'slice(1,-1)'比length-1快,但它仍然打破陣列參考。 – dandavis

+0

不是真的,因爲這種方法是不可變的,我將函數的值傳遞給原始變量 –

2

通過數組循環時就跳過第一個和最後一個元素:

var waypts = []; 
var inputArray = $('#enter-destinations li') 

if(inputArary.length > 2) { 
    for(var i = 1; i < inputArray.length - 1; i += 1) { 
    var thisAddress = $(inputArray[i]).find('input').val(); 
    waypts.push({ 
     location: thisAddress, 
     stopover: true 
    }); 
    } 
} 

console.log(waypts); //show values that were between first and last 
1

直接在jQuery .each()循環中使用索引,以避免首先添加它們。您還避免了2x .find()和2x .push

var waypts = []; 
var elem = $('#enter-destinations li'); 
var total = (elem.length-1); // get last index 
var inputArray = elem.each(function (index) { // index tells you what iteration you are at 
    if(index != total && index != 0){ 
     var thisAddress = $(this).find('input').val(); 
     waypts.push({ location : thisAddress, stopover: true }); 
    } 
}); 
console.log(waypts); //show values that were between first and last 

jsfiddle demo

相關問題