首先感謝Dash 我不再用處處亂找文檔了數組
再次感謝日食記 讓個人看到了世界的美好app
好吧 array有什麼好玩的方法嗎 splice 很好玩的ui
splice 能夠對數組進行刪除 添加 修改操做spa
var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; // 插入 // 找到下表爲2的位置 刪除0個元素 插入 'drum' var removed = myFish.splice(2, 0, 'drum'); // myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon'] // removed is [], no elements removed // 在數組3的位置刪除一個元素 removed = myFish.splice(3, 1); // myFish is ['angel', 'clown', 'drum', 'surgeon'] // removed is ['mandarin'] // 找到下表爲2的位置 刪除1個元素 插入 'drum' // 實際是執行了替換操做 removed = myFish.splice(2, 1, 'trumpet'); // myFish is ['angel', 'clown', 'trumpet', 'surgeon'] // removed is ['drum'] // 在位置0刪除2個 增長3個 removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); // myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon'] // removed is ['angel', 'clown'] // 從某一位置刪除後面全部元素 removed = myFish.splice(3, Number.MAX_VALUE); // myFish is ['parrot', 'anemone', 'blue'] // removed is ['trumpet', 'surgeon']
sort方法
code
array的sort方法一點也不許確orm
var fruit = ['apples', 'bananas', 'Cherries']; fruit.sort(); // ['Cherries', 'apples', 'bananas']; var scores = [1, 2, 10, 21]; scores.sort(); // [1, 10, 2, 21] var things = ['word', 'Word', '1 Word', '2 Words']; things.sort(); // ['1 Word', '2 Words', 'Word', 'word'] // In Unicode, numbers come before upper case letters, which come before lower case letters.
實際上很準確啦 說是根據unicode碼排序的
排序
so 你能夠本身寫規則
ci
function compare(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } // a must be equal to b return 0; }
好比數字排序element
var numbers = [-4, -2, 5, 1, 3]; console.log(numbers.sort());
是不許確的unicode
var numbers = [-4, -2, 5, 1, 3]; numbers.sort(function compare(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } // a must be equal to b return 0; }); console.log(numbers);
解決非Ascii碼字符串排序
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; items.sort(function (a, b) { return a.localeCompare(b); });
concat 擴展數組 沒啥好說的
join 把數組變成字符串
slice 複製指定位置 造成新的array
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; var citrus = fruits.slice(1, 3); // citrus contains ['Orange','Lemon']
有關複製後造成的新數組變量問題
Using slice, create newCar from myCar. var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }; var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']; var newCar = myCar.slice(0, 3); console.log(myCar); console.log(newCar); // Change the color of myHonda. myHonda.color = 'purple'; console.log('The new color of my Honda is ' + myHonda.color); // Display the color of myHonda referenced from both arrays. console.log('myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color); var myCar = []; myCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2, 'cherry condition', 'purchased 1997']; var newCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2]; myCar[0].color = 'purple'; console.log(myCar); console.log(newCar);
從上面的例子看出並不是徹底不同 裏面有Object的話仍是會一塊兒改