Home  >  Article  >  Web Front-end  >  Share example tutorials for JavaScript exercises

Share example tutorials for JavaScript exercises

零下一度
零下一度Original
2017-06-27 10:22:351555browse
Welcome to discuss with everyone~
Basic exercises (1):
#My answer is:
function array_diff(a, b) {  if (b == "") return a;  return a.filter(function(item,index,array) {var flag = false;for(var i=0;i<b.length;i++) {      if(item !== b[i]) flag = true;
    }return flag;
  });
}

The better answer is:

function array_diff(a, b) {  return a.filter(function(x) { return b.indexOf(x) == -1; });
}

Analysis:

Use the filter() method on array a and iteratively determine whether the value in array a exists in array b. When the value of x, i.e. the value of array a, cannot be found in array b, the b.indexOf() method will return -1. The filter() method of an array refers to running a given function on each item in the array and returning an array composed of items that the function will return true.
My idea is a little complicated. The method filter() for iterating the array was thought of, but it was not used properly. The judgment method within the function is not concise enough. I didn't expect to use the indexOf() method to make judgments.

Notes:

filter() method , yes Refers to running a given function on each item in the array and returning an array of items that the function will return true. Uses the specified function to determine whether an item is included in the returned array.
Usage example:
var numbers = [1,2,3,4,5,4,3 ,2,1];
var filterResult = numbers.filter(function(item,index,array) {
return (item> 2);
});
alter(filterResult); //[3,4,5,4,3]
The array iteration method is really commonly used and is used to loop a certain operation on an array. These iteration methods are much simpler than for loop statements, so remember them!
There are five iteration methods: every(), filter(), forEach(), map(), some().

##Basic exercises (2):

My answer is:
var gimme = function (inputArray) {  var newArray = [];  for(var i=0;i<inputArray.length;i++) {
    newArray[i] = inputArray[i];
  }
  newArray.sort(function(a,b) {if(a < b) {      return -1;
    } else if (a> b) {return 1;
    } else {return 0;
    }
  });  return inputArray.indexOf(newArray[1]);
};
The better answer is:

function gimme(a) {  return a.indexOf(a.concat().sort(function(a, b) { return a - b })[1])
}

Analysis:

In the better answer, the concat() method is used on the original array, which can copy the original array and create a new array. Then the new array is sorted and the index value is found for the intermediate value.
My idea is the same as the optimal solution, but the implementation method is still a bit immature. For creating a new array, I don't know that I can use the concat() method to quickly copy it, which also shows that I am not familiar enough with the basic knowledge. In addition, in the sorting method, it turns out that "return a-b" can be used directly, but my method seems very cumbersome.

笔记:

concat()方法可基于当前数组中的所有项创建一个新数组。该方法会先创建当前数组的一个副本,将接收到的参数添加到这个副本的末尾,最后返回新构建的数组。在没有给concat()方法传递参数的情况下,它只是复制。若传递给concat()方法的是一个或多个数组,则该方法会将这些数组中的每一项都添加到结果数组中。若传递值不是数组,则添加到结果数组的末尾。
 
使用例子:
var colors = ["red","green","blue"];
var colors = colors.concat("yellow",["black","brown"]);
alert(colors); // red,green,blue
alert(colors); // red,green,blue,yellow,black,brown
 
重排序方法:使用sort()方法可以进行排序,但仍可能会出现一些问题,因此使用比较函数,可以避免这个问题。
对于大多数数据类型可使用,只需要将其作为参数传递给sort()方法即可:
function compare(value1,value2) {
     if(value1 < value2) {
return -1;
} else if (value1> value2) {
          return 1;
     } else {
          returm 0;
     }
}
对于数值型或其他valueOf()方法会返回数值类型的对象类型,可以使用更简单的比较函数:
function compare(value1,value2) {
     return value2 - value1;
}
 
基础练习(3):
 


我的解答为:
function minMax(arr){  var newarr = [];
  newarr.push(Math.min.apply(Math,arr));
  newarr.push(Math.max.apply(Math,arr));  return newarr;
}

较优解答为:

function minMax(arr){  return [Math.min(...arr), Math.max(...arr)];
}

分析:

这道题目就很简单了,较优解答中的扩展语法( spread syntax)也在练习一中提及了。我的写法还是太谨慎了,是不是应该大胆一些呢?
 
基础练习(4):
 


我的解答为:
function XO(str) {   var str = str.toLowerCase();   var countx = 0;   var counto = 0;   for(var i=0;i<str.length;i++) {     if(str[i] === "x") {
       countx++;
     }     if(str[i] === "o") {
       counto++;
     }
    }if(counto == countx) {      return true;
    } else {      return false;
    }
}

较优解答为:

function XO(str) {var a = str.replace(/x/gi, ''),
          b = str.replace(/o/gi, '');return a.length === b.length;
}

分析:

较优解使用的是replace()方法,结合正则表达式的使用,对原字符串str分别将x和o用空字符串替换得到a和b字符串,比较a和b字符串的长度,从而得到结果。我的解答方法呢,因为实在想不到可以使用什么方法,所以用的最原始的方法,仿佛自己在做C语言的题目。
 
笔记:
replace()方法,该方法接受两个参数,一个参数可以是一个RegExp对象或者一个字符串,第二个参数可以是一个字符串或者是一个函数。若第一个参数是字符串,指挥替换第一个子字符串。要想替换所有子字符串,是提供一个正则表达式,并且指定全局标志。
 
使用例子:
var text = "cat,bat,sat,fat";
var result = text.replace("at","ond");
alert(result); //"cond,bat,sat,fat"
 
result = text.replace(/at/g,"ond");
alert(result); //"cond,bond,song,fond"
 
 总结:
今天的知识点主要是数组的迭代方法中的一种filter()方法、数组操作方法中的concat()方法以及字符串的replace()方法。filter()方法可用于使用函数判断数组中各项的值中返回true值的结果所组成的数组。concat()可以复制和创建新数组。而replace()方法可以替换字符串中的一个或多个值。
从这三天的练习来看,对于数组的各种方法也逐渐使用得熟练起来了。但是其他类型的各种方法还是一种挑战。而我的解答也要从比较冗余的语句,写出更为简洁而有效的语句了。继续加油吧!
 
 

The above is the detailed content of Share example tutorials for JavaScript exercises. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn