JavaScript manipulation arrays

Source: Internet
Author: User
Tags array sort new set shallow copy sublime text javascript array

An array is described as a linear set of stored elements that can be arbitrarily accessed by an index.

Almost all programming languages have similar data structures, but the arrays in JavaScript are slightly different.

arrays in JavaScript are a special kind of object , so the array is not as efficient as an array in other languages.

Also because arrays are treated as objects in JavaScript, there are many properties and methods that can be used for reprogramming.

Here's a quick introduction to how arrays are used in JavaScript.

Note: All of the following JavaScript code runs in Jsshell , and some methods may not work in other environments, such as browsers and sublime text.

"The use of Jsshell"

/* Js-shell Download: Http://mzl.la/MKOuFY According to the system and language to choose different versions to download, downloaded directly open Js-shell terminal for use *//**************** Some JS methods commonly used in Js-shell are ***************/print ();  Print the page/print Putstr ("") directly on the terminal; Display hint information var num = ReadLine ();  Accept user-entered information

"Operation of arrays in JavaScript"

/**************** JavaScript array operation ***************///Creating an array: var arr1 = []; var arr2 = [1,2,3,4,5];var arr3 = new Array (), var arr4 = new Array (ten), var arr5 = new Array (1,2,3,4,5);//JS array elements do not have to be the same kind    Type: var arr6 = [1, "Watermelon", null,true];//determines whether an object is an array: Array.isarray (arr); Display true/false//read-write array for (Var i=0;i<num.length;i++) {print (num[i]);}   Generate array by string split (delimiter) var sentence = "This is a sentence ..."; var words = Sentence.split ("");    Use spaces to split strings in a word array///array operations//Shallow copy: The new array still points to the original array, modifying the original array then the contents of the new array change var nums = [1,2,3,4,5];var arr = nums;   Directly speaking nums assignment to arrnums[0] = 100;   Modifies the contents of the first element of the Nums array print (arr.[0]); The contents of the first element of the ARR array also changed//deep copy: That is, each element of the original array is copied for (Var i=0;i<nums.length;i++) {Arr[i] = nums[i];} Nums[0] = 999;print (arr[0]);//At this time the first element of the ARR array does not change, still the access operation for the 1//array//Lookup element indexof () if not found then return -1var names = ["Bob", "Lily", "    John "," Eileen "," Sivan "];var name = ReadLine ();  The user enters a name to look up var position = Names.indexof (name); The function returns the index of the found element in the array if (position>=0) {//If the user finds the name in the array that exists in the print ("Found" + name + "At position" + postion);} Else{print (name + "not found in array ...");} LastIndexOf ();//The string representation of the array//tostring () method var days = ["Monday", "Tuesday", "Wednesday", "Thursday"];var days_string = Days.tostring ();p rint (DAYS_STIRNG); Output Monday,tuesday,wednesday,thursday//join () method var days_string1 = Days.join ();p rint (days_join);//Output Monday,tuesday , Wednesday,thursdayprint (days);//Output monday,tuesday,wednesday,thursday//the ToString () method is automatically called when the print () method is used directly on a mathematical /created new array by an existing array var nums = [1,2,3,4];var names = [' Jane ', ' Sam ', ' Mike ', ' Bob '];var arr = nums.concat (names);p rint (arr);//Output , 3,4,jane,sam,mike,bob//splice () intercepts the array to create a new array (which will have an effect on the original array) var numbers = [1,2,3,4,5,6,68,7];var arr = Numbers.splice (3,4); Start capturing 4 elements of print (arr) from an element indexed as 3 (third);//output 4,5,6,68//push () adds an element at the end of the array var seasons = ["Summer", "Autumn"];var push =   Seasons.push ("Winter"); Also add multiple elements//unshift () to the beginning of an array, add the element var unshift = Seasons.unshift ("Spring"),//pop () Delete the element at the end of the array; var pops = Seasons.pop ();// Shift () Delete the element at the beginning of the array var shift = Seasons.shift ();//Add and remove elements from the middle of the array var nums = [1,2,3,4,6,7,8];var addnums = [9,9,9];nums.splice (2,0,addnums);p rint (nums); Output 1,2,9,9,9,3,4,5,6,7,8//Array sort//reverse () method var nums = [1,2,3,4];var arr = Nums.reverse ();p rint (arr);//Output 4,3,2,1//     The sort () method is var name = ["Bob", "Alice", "Cindy"];var arr = Name.sort ();p rint (arr); The output Alice,bob,cindy//sort () method sorts only for strings based on the dictionary order,//If it is a numeric type, you need to pass in a comparison function as the parameter function compare (num1,num2) {return NUM1- num2;}   var nums = [1,32,45,12];var arr = nums.sort (compare); Pass in Function name only print (arr);//Output 1,12,32,45/**************** iterator Method ***************///foreach () executes a method function for each element in the array Square (num) {print (num,num*num);} var num = [1,2,3,4];num.foreach (square);//Output 1 4,3 the 9//every () method takes a function with a return value of type bool as a parameter,//If the function returns true for all elements in the array, Then the method returns truefunction IsEven (num) {return num% 2 = = 0;} var nums = [2,4,6,8];var even = Nums.every (IsEven), if (even) {print ("All numbers is even ...");} Else{print ("Not all numbers is even ...");} Output "All numbers is even ..." the method returns truefunction IsEven (num) {Re, as long as there is an element in the array of//some () method that enables the function to return true.Turn num% 2 = = 0;} var nums = [2,3,4,5,6];var even = Nums.some (IsEven);p rint (even);//output true//reduce ()//array-by-item function Add (Runningtoda L,currentvalue) {return runningtodal + CurrentValue;}     var nums = [1,2,3,4,5];var sum = nums.reduce (add);p rint (sum); The output 15//links the array elements into a long string function concat (accumulatedstring,item) {return accumulatedstring + item;}     var words = ["This", "was", "a", "good", "Day"];var string = Words.reduce (concat);p rint (string);   Output "This was a good day" var string2 = Words.reduceright (concat);//execute print from right to left (string2); Output "Day good A was this"/* iterator method for generating a new array *///map () is similar to foreach (), which performs an operation on each element in an array, but returns a new set of function curve (num) {return num +5;} var nums = [1,2,3,4];var arr = Nums.map (curve);p rint (arr);//output 6,7,8,9function First (word) {return word[0];} var names = ["Alice", "Bob", "Cindy", "Daniel"];var arr = Names.map (first); The results are ["A", "B", "C", "D"]print (arr). Join ());//Output "a,b,c,d" Print (Arr.join (""));//Output "ABCD"//filter () The input return value is a function name of type bool as a parameter, and each element in the array executes a function,// However, the returned result is an element that returns a value of True for the function//E.g to determine the parity of array elements function IsEven (num) {return num%2 = 0;//even}function isodd (num) {return num%2! = 0;//odd}var num = [];for (VA R i=0;i<10;i++) {Num[i] = i+1;} var evens = Num.filter (IsEven);p rint ("even numbers:");p rint (evens);//output 2,4,6,8,10var odds = Num.filter (isodd);p rint (" ODD numbers: ");//Output 1,3,5,7,9print (odds);//e.g Judging whether the score is qualified function passing (num) {return num>=60;} var grade = [];for (var i=0;i<20;i++) {Grade[i] = Math.floor (Math.random () *101);} var pass = grade.flter (passing);p rint ("All Grades:");p rint (grade);p Rint ("Passing Grades:");p rint (pass);// e.g. filtering string array function del (str) {if (Str.indexof ("CIE") >-1) {return true;} Else{return false;}} var words = ["Receive", "decide", "Percieve", "deceit", "convince"];var misspelled = Word.filter (Del);p rint (misspelled) ;//Output "Percieve"

JavaScript manipulation arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.