Javascript数据类型 - Array(上)

ja-array-operation

一、 声明数组

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()

总结

Array In ES5

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容