JS淬煉: Array入門

Javascript arrays are used to store multiple values in a single variable.

Disclaimer: This is my note for Javascript study where part of the content is copied from other sources. Please go to the Reference part to see the original posts.

Array is an Object

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements", rather than a self-defined named key.

Creating an Array

// method1
var cars = ["Saab", "Volvo", "BMW"];

// method2, exactly the same but complicated, should avoid
var cars = new Array("Saab", "Volvo", "BMW");

Never put a comma after the last element (like "BMW",).
The effect is inconsistent across browsers.

Array Properties and Methods

var x = cars.length;  // The length property returns the number of elements
var y = cars.sort();  // The sort() method sorts arrays
var z = cars.reverse(); // The reverse() method reverts arrays

Popping and Pushing

The pop() method removes the last element from an array and returns the value that was popped.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop();      // the value of x is "Mango"

The push() method adds a new element to an array (at the end), and returns the new array length.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi");   //  the value of x is 5

Shifting and Unshifting

Shifting is equivalent to popping, working on the first element instead of the last.
The shift() method removes the first array element and "shifts" all other elements to a lower index, and return the item that is shifted out.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();           // Removes the first element "Banana" from fruits

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements, and return the new length.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");    // Adds a new element "Lemon" to fruits

Splicing an Array

splice() can be used to add new elements to Array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
// [ 'Banana', 'Orange', 'Lemon', 'Kiwi', 'Apple', 'Mango' ]

The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

Joining Arrays

The concat() method

var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys);  // Concatenates (joins) myGirls and myBoys

Using the ES6 spread syntax

const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr3 = [...arr1, ...arr2] //arr3 ==> [1,2,3,4,5,6]

Deleting Elements

Using the JavaScript operator delete

var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];  // Changes the first element in fruits to undefined

Using delete may leave undefined holes in the array. Use pop() or shift() instead.

Using splice to delete an element without holes.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);        // Removes the first element of fruits

The first parameter (0) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.

Using filter to delete an element without holes.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var toDelete = "Apple";
fruits = fruits.filter(function(value) {
    return value != toDelete;
});
// [ 'Banana', 'Orange', 'Mango' ]

Finding an Element

The find() method returns the value of the first element in an array that pass a test (provided as a function).

var ages = [3, 10, 18, 20];

function checkAdult(age) {
    return age >= 18;
}

function myFunction() {
    document.getElementById("demo").innerHTML = ages.find(checkAdult);
}

Slicing an Array

The slice() method slices out a piece of an array into a new array. This example slices out a part of an array starting from array element 1 ("Orange"):

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
// Orange,Lemon,Apple,Mango

The slice() method can take two arguments like slice(1,3).
The method then selects elements from the start argument, and up to (but not including) the end argument.

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);

If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the array.

How to Recognize an Array

Solution 1 (ES5)

Array.isArray(fruits);     // returns true

Solution 2 create your own isArray function.

function isArray(x) {
    return x.constructor.toString().indexOf("Array") > -1;
}

Solution 3 use instanceof operator

fruits instanceof Array     // returns true

Reference

http://www.w3schools.com/js/js_arrays.asp
http://www.w3schools.com/js/js_array_methods.asp
http://www.w3schools.com/jsref/jsref_filter.asp
http://www.w3schools.com/jsref/jsref_find.asp

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子揽乱,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)沿后,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來朽砰,“玉大人尖滚,你說我怎么就攤上這事∏迫幔” “怎么了漆弄?”我有些...
    開封第一講書人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長造锅。 經(jīng)常有香客問我撼唾,道長,這世上最難降的妖魔是什么哥蔚? 我笑而不...
    開封第一講書人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任倒谷,我火速辦了婚禮,結(jié)果婚禮上糙箍,老公的妹妹穿的比我還像新娘渤愁。我一直安慰自己,他們只是感情好深夯,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開白布抖格。 她就那樣靜靜地躺著,像睡著了一般咕晋。 火紅的嫁衣襯著肌膚如雪他挎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,708評(píng)論 1 305
  • 那天捡需,我揣著相機(jī)與錄音,去河邊找鬼筹淫。 笑死站辉,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的损姜。 我是一名探鬼主播饰剥,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼摧阅!你這毒婦竟也來了汰蓉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤棒卷,失蹤者是張志新(化名)和其女友劉穎顾孽,沒想到半個(gè)月后祝钢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡若厚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年拦英,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片测秸。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡疤估,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出霎冯,到底是詐尸還是另有隱情铃拇,我是刑警寧澤,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布沈撞,位于F島的核電站慷荔,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏关串。R本人自食惡果不足惜拧廊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望晋修。 院中可真熱鬧吧碾,春花似錦、人聲如沸墓卦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽落剪。三九已至睁本,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間忠怖,已是汗流浹背呢堰。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留凡泣,地道東北人枉疼。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像鞋拟,于是被迫代替她去往敵國和親骂维。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容