[英]How to remove all the odd indexes (eg: a[1],a[3]..) value from the array
我有一個數組,如var aa = ["a","b","c","d","e","f","g","h","i","j","k","l"];
我想刪除位於偶數索引上的元素。 所以輸出將是 line aa = ["a","c","e","g","i","k"];
我試過這樣
for (var i = 0; aa.length; i = i++) {
if(i%2 == 0){
aa.splice(i,0);
}
};
但它不起作用。
使用Array#filter
方法
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]; var res = aa.filter(function(v, i) { // check the index is odd return i % 2 == 0; }); console.log(res);
如果您想更新現有數組,請執行此操作。
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"], // variable for storing delete count dCount = 0, // store array length len = aa.length; for (var i = 0; i < len; i++) { // check index is odd if (i % 2 == 1) { // remove element based on actual array position // with use of delete count aa.splice(i - dCount, 1); // increment delete count // you combine the 2 lines as `aa.splice(i - dCount++, 1);` dCount++; } } console.log(aa);
另一種以相反順序(從最后一個元素到第一個元素)迭代 for 循環的方法。
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]; // iterate from last element to first for (var i = aa.length - 1; i >= 0; i--) { // remove element if index is odd if (i % 2 == 1) aa.splice(i, 1); } console.log(aa);
您可以通過這樣做刪除所有備用索引
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]; var x = []; for (var i = 0; i < aa.length; i = i + 2) { x.push(aa[i]); } console.log(x);<\/code><\/pre>
"
您可以使用.filter()
aa = aa.filter((value, index) => !(index%2));
您可以使用如下所示的臨時變量。
var a = [1,2,3,4,5,6,7,8,9,334,234,234,234,6545,7,567,8]
var temp = [];
for(var i = 0; i<a.length; i++)
if(i % 2 == 1)
temp.push(a[i]);
a = temp;
在 Ecmascript 6 中,
var aa = ["a","b","c","d","e","f","g","h","i","j","k","l"];
var bb = aa.filter((item,index,arr)=>(arr.splice(index,1)));
console.log(bb);
const aa = ["a","b","c","d","e","f","g","h","i","j","k","l"];
let bb = aa.filter((items, idx) => idx % 2 !== 0)
我在這里讀到splice
具有 O(N) 時間復雜度。 不要循環使用它!
刪除奇數索引的簡單替代方法:
for (let idx = 0; idx < aa.length; idx += 2)
aa[idx >> 1] = aa[idx];
aa.length = (aa.length + 1) >> 1;
我使用x >> 1
作為Math.floor(x/2)
的快捷方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.