2013-03-26 140 views
0

我不明白爲什麼拼接方法不適合我。我有一個數組,看起來像:(它實際上是更大的,但我不想弄亂頁)插入對象文字到數組中

var navItems = [ { 
        "content": "Panels", 
        "icon": "panels" 
       }, 
       { 
        "content": "Samples", 
        "icon": "sample" 
       }]; 

我要插入一個項目在中間說:

var testNavItems = navItems.splice(1, 0, { 
        "content": "New Nav", 
        "icon": "New Nav" 
        }); 
console.log(testNavItems); 

OR

var testNavItems = navItems.push({ 
        "content": "New Nav", 
        "icon": "New Nav" 
        }); 
console.log(testNavItems); 

我得到一個空的數組。這在JS中可能嗎?

+1

['.splice'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice)返回已元素刪除,['.push'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push)返回數組的新長度。始終檢查文檔。 – 2013-03-26 18:43:23

回答

3

.push.splice不創建新數組。他們修改原始數組。

嘗試

console.log(navItems);