JS Pen Test series two--array

Source: Internet
Author: User
Tags array sort shallow copy

(1) Quickly create an array containing 100 values of 0 elements.

Method One:

var arr = new Array (+); for (Var i=0;i<100;i++) {  arr[i] = 0;}

Method Two:

var arr = new Array (+); Arr.join (' 0 '). Split (');  Note This method results in a character type of 0

Which answer will the interviewer like?

(2) Classic array de-weight problem

Array de-weight can be said to be the major companies in the front-end written in the common problems, the following list of several typical solutions

Method One: Traditional double-cycle contrast method

function Unique0 (arr) {  var n = [];//A new temporary array for  (Var i=0,l=arr.length; i<l; i++)//Traversal target array  {    var mark = 1; Mark field for    (Var j=0;j<n.length+1;j++) {//Traverse temporary array      if (arr[i] = = = N[j]) {        mark = 0;        break;      }    }             Mark && N.push (Arr[i]);  }  return n;}

Method Two: Using indexof method

function Unique1 (arr) {  var n = [];//A new temporary array for  (Var i=0,l=arr.length; i<l; i++) {//traverse the current array      // If the current array of I has been saved into a temporary array, then skip,    //Otherwise push the current item to the temporary array inside    if (N.indexof (arr[i]) = = 1) n.push (Arr[i]);  }  return n;}

Method Three: Take advantage of object property uniqueness

function Unique2 (arr) {   var n = [];//Store new array   var json = {};//Take advantage of object property uniqueness for   (var i=0,l=arr.length; i<l; i++) {//traverse the current array      if (!json[arr[i]]) {//Determine if JSON has arr[i] attribute        N.push (arr[i]);        Json[arr[i]] = 1; Tag json new attribute Arr[i]      }    }   return n;}

Three methods have their own advantages and disadvantages, the first method uses two loops, so when the array is very large when the efficiency is the lowest, the second use of the ES5 IndexOf method, if not consider the low version of IE (otherwise have to implement this method) comparison recommendation, the last method actually hides a bug: Since this approach leverages the uniqueness of object properties, when assigning an array element to an object property, the element is converted to a string type: Unique2 ([' Max ', [MAX]]) returns the wrong result [""], meaning that this method is not feasible in a multidimensional array scenario.

(3) Delete the second and third items of the given array, and then press the last element of the array into the head of the array

Here we look at the common methods of array manipulation, we take the var arr = [1,2,3,4,5] As the initial array, first to see the results of the solution:

Arr.splice. Unshift (Arr.pop ()); ==>[1, 4]

The result of this solution is not what we expected, because according to the requirements of the topic should be [5,1,4], then where is the problem? The reason is that this can not be written in this way, because the return result of the Splice method is not the original array, but the truncated array fragment, so the correct answer only need to change:

Arr.splice (Arr.unshift); (Arr.pop ()); ==>[5,1,4]

(4) Fill in the blanks to achieve output [' C ', ' d ']

var data = {A:1,b:2,c:3,d:4};object.keys (data). filter (function (x) {  return ___;})

First of all, if you do not understand the new method of Object.keys or filter two ES5, this problem is difficult to answer. If these two methods are hard for you, then you are close to success, because actually only need to underline the "X" directly, will return [' A ', ' B ', ' C ', ' d '], then how to return the result is [' C ', ' d '], smart you must have thought of is x > ' B '. ' C ', ' d ' and ' B ' compare to true so it is possible to return, while ' a ', ' B ' elements are compared to false and not returned.

(5) The code implements the following requirements

var arr = [1,2];var New_arr; Required implementation: New_arr = = = Arr ==>falsenew_arr[0] = = Arr[0]; ==>TRUENEW_ARR[1] = = arr[1]; ==>true

This topic first must understand the meaning, understands the question person intention: The topic request New_arr cannot strictly equal arr, but the inside element is equal. We know that implementing the elements within the array is quite simple, where the direct New_arr = arr is okay, but if the simple assignment does not satisfy the first condition, two arrays cannot be strictly equal. So, what the question-makers want the answer to know is the understanding of the object reference assignment, how to implement the object value passing instead of a reference to pass two knowledge points. The solution to the value passing of an array is simply to iterate through the elements of the original array, and of course there is no need for us to write a traversal:

var New_arr = Arr.slice ();//orvar New_arr = Arr.concat ();

The above two methods can achieve the requirements of the topic.

(6) Randomly select 10 non-repeating random integers in 5-105, and then sort by small to large

Here are two points, do not repeat the acquisition of random numbers, arrays of numbers, where the array arrangement can not be directly with the sort (), but must pass a function parameter, otherwise it will not get the expected result, because the array sort by default is the comparison by character:

Method One:

  var arr = []; Store non-repeating random number  var n;  while (Arr.length <) {    n = math.round (5+math.random () *100);    Arr.indexof (n) ==-1&&arr.push (n);  Arr.sort (function (A, b) {return-A-B});  Console.log (arr);

Method Two:

  var arr = []; Store all possible numbers for  (var i=0;i<=100;i++) {    arr[i] = 5+i;  }  Arr.sort (function (A, b) {return 0.5-math.random ();}). Slice (0,10). Sort (function (A, b) {return-A-b});

Method Two of the idea and method of a distinctly different, here is the whole range of the integer stored in arr, and then call--sort (order scrambled)--slice (take the first 10 elements)--sort (sorted by size return)

(7) How to make all browsers compatible with ES5 array foreach method

Array.prototype.forEach | | (Array.prototype.forEach = function (fun) {  for (var i = 0; i < this.length; i++) {Fun    (this[i], I, this); 
   }})

First detect whether the browser supports foreach, if not supported to write a method of the same name to implement the same function, other similar problems can be resolved by this approach.

(8) Deep Clone object

var cloneobj = function (obj) {    var str, newobj = Obj.constructor = = = Array? [] : {};    if (typeof obj!== ' object ') {        return obj;    } else if (window. JSON) {        str = json.stringify (obj),//Serialization object        newobj = Json.parse (str);//Restore    } else {for        (var i in obj) {            Newobj[i] = typeof obj[i] = = = ' object '?             Cloneobj (Obj[i]): Obj[i];         }    }    return newobj;};

In JS in the assignment of objects, often hear deep copy and shallow copy, shallow copy is the direct object assignment to use a reference address, but most of the time we do not want this, but want to be completely independent between the objects, this time requires deep cloning, the basic principle is the object of all the properties of the traversal replication.

JS Pen Test series two--array

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.