Javascript數(shù)據(jù)類型 - Array(上)

ja-array-operation

一混稽、 聲明數(shù)組

There are two ways to declare an Array in javascript:

  • Using Array literals?—?it is just a pair of square brackets followed by zero or more value items separated by commas like —
var foo = [];
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  • Using Array constructor?—?it is just creating an array using new keyword like —
var foo = new Array();
var days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

二洽洁、屬性(Properties)

length?—?the length property of an array is the largest positive integer key plus one.

三、方法(Methods)

There are many methods associated with arrays in javascript, some methods modify the existing array(Mutator Methods), some are used to access values or return some required representation and do not change the existing array(Accessor Methods), some for looping over array items(Iterator Methods) and so on. Lets explore few of most commonly used these methods and categories on the bases of there nature.

1. Mutator Methods

  • Array.prototype.push() ?— ?push adds one or more elements to the end of an array and returns the updated length of array.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.push('Saturday');  //7
console.log(days);      // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  • Array.prototype.pop() — pop method removes the last element from an array and returns that removed element.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.pop(); //Friday
console.log(days); //["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"]
  • Array.prototype.shift() — similar to pop method, shift removes the first element from an array and returns that element.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.shift();      // Sunday
console.log(days); // [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
  • Array.prototype.unshift() ?—? similar to push method, unshift method add one or more elements to the front of an array and returns the updated length of the array.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.unshift('Saturday'); // 7
console.log(days);        // [ "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
  • Array.prototype.sort()?—?this method sorts the elements of an array and returns the new sorted array.
var numbers = [3,45,5,7,32,56,87,11];
numbers.sort(); //[11, 3, 32, 45, 5, 56, 7, 87]
console.log(numbers);  //[11, 3, 32, 45, 5, 56, 7, 87]
  • Array.prototype.reverse()— this method reverses the order of the elements of an existing array i.e. the first element of array becomes the last, and the last element becomes the first element.
var numbers = [3,45,5,7,32,56,87,11];
numbers.reverse(); //[11, 87, 56, 32, 7, 5, 45, 3]
  • Array.prototype.splice()?—?this method modify the existing array by adding new elements or removing elements from the array. Splice method can take any number of arguments, first is the start index and it is required, second is the delete count i.e. the number of element to delete from the start index, if given 0 then nothing is going to delete, it is optional and rest of the arguments are the elements to be added at given index.
// Syntax - 
// array.splice(start, deleteCount, item1, item2, ...)

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.splice(2,1);   // ["Tuesday"]
console.log(days);  // ["Sunday", "Monday", "Wednesday", "Thursday", "Friday"]
days.splice(2,0,'Tuesday');
console.log(days)   // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

2. Accessor Methods —

  • Array.prototype.slice()?—?slice method can takes two arguments, first is start index and second is end index and returns an array that has only the elements between those two indexes. The start index is required, the end index optional, if end index is not given then extract till end of the array.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.slice(2,4); //["Tuesday", "Wednesday"]
days.slice(3); //["Wednesday", "Thursday", "Friday"]
  • Array.prototype.concat()?—?this method is used to concatenate or glue arrays together and returns a new array concatenated array.
var week_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
var weekend_days = ['Saturday', 'Sunday'];
week_days.concat(weekend_days); //["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  • Array.prototype.join()— this method flattened all the elements of the array to a single string. The argument passed to join is glued between array elements while joining to string.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.join('-'); //Sunday-Monday-Tuesday-Wednesday-Thursday-Friday
  • Array.prototype.includes()?—?return true or false whether an array contains a certain element, which is passed as an argument in the includes function.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.includes('Sunday'); //true
days.includes('sunday'); //false
  • Array.prototype.indexOf()— Returns the index of first (least) occurrence of element within the array which is given, or -1 if none is found. It also take second argument which is optional and specify from where to start.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.indexOf('Tuesday');    // 2
days.indexOf('Tuesday', 4); // -1
days.indexOf('March');      // -1
  • Array.prototype.lastIndexOf()— Returns the index of last (greatest) occurrence of element within the array which is given, or -1 if none is found. It also take second argument which is optional and specify from where to start.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
days.lastIndexOf('Tuesday');    // 2
days.lastIndexOf('Tuesday', 4); // 2
days.lastIndexOf('March');      // -1

3.Iteration methods —

  • Array.prototype.filter()?—?It iterate over the every element of the given array and return a new array having only those element which the provided filtering function returns true.
var random_numbers = [2,4,5,6,7,9,34,26,45,39];
random_numbers.filter(function(element){
return element % 2;
});
//[5, 7, 9, 45, 39]
  • Array.prototype.find()?—?similar to filter method, it also iterate over array and return only the first element of array which return true with the provided conditions or functionality.
var random_numbers = [2,4,5,6,7,9,34,26,45,39];
random_numbers.find(function(element){
 return element > 20;
});
//34
  • Array.prototype.forEach() —It iterate and calls a function for each element in the array. This callback function can be called with three parameters, first is element of array, second is index of that element and third is the array being traversed.
var random_numbers = [1,2,4,5,6,7];
function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}
random_numbers.forEach(logArrayElements);
//a[0] = 11
//a[1] = 21
//a[2] = 41
//a[3] = 51
//a[4] = 61
//a[5] = 71
  • Array.prototype.map()?—?Creates a new array with the results of calling a provided function on every element in this array.
var random_numbers = [1,2,4,5,6,7];
var doubledArray = random_numbers.map(function(element){
  return element * 2;
});
console.log(doubledArray); //[2, 4, 8, 10, 12, 14]
  • Array.prototype.reduce() — It traverses the array (from left-to-right) and invokes a callback function on each element. The value returned is the progressively passed from callback to callback, and at the end reduce() returns the cumulative value.
// Syntax - 
// array.reduce(function(total, currentValue, currentIndex, arr), initialValue);

var rockets = [
     {country:'Russia', launches:32 }, { country:'US', launches:23 },  { country:'China', launches:16 }, 
     { country:'Europe(ESA)', launches:7 }, { country:'India', launches:4 }, { country:'Japan', launches:3 } 
];  
var sum = rockets.reduce(function(total, elem) {   return total + elem.launches; }, 0);    
sum // 85
  • Array.prototype.every()

  • Array.prototype.some()

4.

toString()
valueOf()

總結(jié)

Array In ES5

參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市笋熬,隨后出現(xiàn)的幾起案子旺隙,更是在濱河造成了極大的恐慌,老刑警劉巖铡俐,帶你破解...
    沈念sama閱讀 221,198評論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異脓钾,居然都是意外死亡,警方通過查閱死者的電腦和手機握截,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評論 3 398
  • 文/潘曉璐 我一進店門飞崖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人谨胞,你說我怎么就攤上這事固歪。” “怎么了畜眨?”我有些...
    開封第一講書人閱讀 167,643評論 0 360
  • 文/不壞的土叔 我叫張陵昼牛,是天一觀的道長。 經(jīng)常有香客問我康聂,道長贰健,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,495評論 1 296
  • 正文 為了忘掉前任恬汁,我火速辦了婚禮伶椿,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘氓侧。我一直安慰自己脊另,他們只是感情好,可當我...
    茶點故事閱讀 68,502評論 6 397
  • 文/花漫 我一把揭開白布约巷。 她就那樣靜靜地躺著偎痛,像睡著了一般。 火紅的嫁衣襯著肌膚如雪独郎。 梳的紋絲不亂的頭發(fā)上踩麦,一...
    開封第一講書人閱讀 52,156評論 1 308
  • 那天枚赡,我揣著相機與錄音,去河邊找鬼谓谦。 笑死贫橙,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的反粥。 我是一名探鬼主播卢肃,決...
    沈念sama閱讀 40,743評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼才顿!你這毒婦竟也來了莫湘?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,659評論 0 276
  • 序言:老撾萬榮一對情侶失蹤娜膘,失蹤者是張志新(化名)和其女友劉穎逊脯,沒想到半個月后优质,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體竣贪,經(jīng)...
    沈念sama閱讀 46,200評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,282評論 3 340
  • 正文 我和宋清朗相戀三年巩螃,在試婚紗的時候發(fā)現(xiàn)自己被綠了演怎。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,424評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡避乏,死狀恐怖爷耀,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情拍皮,我是刑警寧澤歹叮,帶...
    沈念sama閱讀 36,107評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站铆帽,受9級特大地震影響咆耿,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜爹橱,卻給世界環(huán)境...
    茶點故事閱讀 41,789評論 3 333
  • 文/蒙蒙 一萨螺、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧愧驱,春花似錦慰技、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至糟红,卻和暖如春艾帐,著一層夾襖步出監(jiān)牢的瞬間蚯舱,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評論 1 271
  • 我被黑心中介騙來泰國打工掩蛤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留枉昏,地道東北人。 一個月前我還...
    沈念sama閱讀 48,798評論 3 376
  • 正文 我出身青樓揍鸟,卻偏偏與公主長得像兄裂,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子阳藻,可洞房花燭夜當晚...
    茶點故事閱讀 45,435評論 2 359

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

  • 蝶戀花.家 徐 宏 廿八初婚晰奖,家如概念。異地飄泊無求腥泥,卻道麻友...
    sunxuhong閱讀 210評論 0 1
  • 新巔峰孟母堂一期工程主體二層封頂結(jié)束蛔外,這是一個劃時代的時刻蛆楞,新巔峰人經(jīng)過十四年的努力,歷經(jīng)4000場報告會夹厌,上百場...
    每個人的孟母堂閱讀 314評論 0 1
  • 6.40~8.00 上廁所豹爹,刷牙洗臉,喝水矛纹,煮玉米臂聋,弄碎米飯,把飯盒拿廚房或南,把冰箱菜端房間孩等,炒蛋炒飯,剝蔥采够,裝便當...
    蓮喵喵閱讀 235評論 0 0
  • 小酒窩長睫毛迷人的無可救藥 我放慢了步調(diào)感覺像是喝醉了 終于找到心有靈犀的美好 一輩子暖暖的好我永遠愛你到老 ...
    沐天晴閱讀 716評論 2 1