[英]Using javascript, what is an efficient way of changing the length of elements in a jagged array?
我試圖找到一種有效的方法來改變數組的長度和數組中的元素。 例如,如果我有
var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]
我想結束
var arr = [["Name", "Age"], ["Luke Skywalker", "22"], ["Yoda", "900"]]
我已經編寫了一些代碼來做到這一點,但我想確保我改變嵌套數組長度的方式(因為沒有更好的術語)盡可能有效。
我有:
var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]
arr.length = 3; // Removes the Obi Wan entry
console.log(arr);
for(var i = 0; i < arr.length; i++){
arr[i].length = 2 // Removes lightsaber color
};
console.log(arr)
我希望優化的代碼是 for 循環。 我將使用更大的數據集。 謝謝
我希望優化的代碼是 for 循環。
如果您的意思是運行時效率,那么您正在做的事情已經和它將獲得的一樣高效。 任何使用其他東西(如slice
或map
)的東西都會變慢。
請注意,這真的不太可能重要。 除非您已經確定此循環是性能障礙,否則不要擔心。 如果您已經確定,這是一個性能攔截器,陣列(或多個)必須是非常大的。 :-) 即使您要處理 100,000 個數組,我也不認為這會花費大量時間。
讓我們來了解一下:
const now = performance.now ? performance.now.bind(performance) : Date.now.bind(Date); // Create an array with 110k entries, each being five entries long. const arr = Array.from({length:110000}, () => ["a", "b", "c", "d", "e"]); // Start timing const start = performance.now(); // Cut it down to 100k entries arr.length = 100000; // Trim them to two entries for (const entry of arr) { entry.length = 2; } // Done timing const elapsed = now() - start; console.log("Elapsed: " + elapsed + "ms");
我在我的工作站上使用 Brave(如 Chrome,使用 V8 作為 JavaScript 引擎)獲得了大約 20 毫秒的時間。
這不是一個嚴格的基准,但它給了我們一個想法......
只是一個小小的改進,但有時Array.prototype.splice
比設置數組的長度來截斷數組更快:
var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]] arr.splice(3); // Removes the Obi Wan entry console.log(arr); for(var i = 0; i < arr.length; i++){ arr[i].splice(2) // Removes lightsaber color } console.log(arr);
有關比較兩個版本的基准,請參閱http://jsben.ch/BmvNj 。
您可以使用array.splice :
arr[i] = arr[i].splice(0, 2);
嘗試這個:
var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]] arr.length = 3; // Removes the Obi Wan entry console.log(arr); for(var i = 0; i < arr.length; i++){ arr[i] = arr[i].splice(0, 2); }; console.log(arr)
好吧,你可以這樣做:
arr.forEach(function(item) { item.splice(-1) });
splice(-1)
修改原始數組,刪除其上的最后一項
您可以將Array.map
與Array.slice
結合使用:
let arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]; let result = arr.map(person => person.slice(0, 2)); console.log(result);
這是您的要求的一種簡單易讀的方式。
var arr = [["Name", "Age", "Lightsaber Color"], ["Luke Skywalker", "22", "Green"], ["Yoda", "900", "Green"], ["Obi Wan Kenobi", "59", "Blue"]]
for(var i=0; i< arr.length;i++){
arr[i].splice(-1, 1)
}
console.log(arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.