search
HomeWeb Front-endJS TutorialShare example tutorials for JavaScript exercises

Share example tutorials for JavaScript exercises

Jun 27, 2017 am 10:22 AM
javascriptjstidynotespractise

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><div class="cnblogs_code"></div>
<p>The better answer is: <span style="font-family: " microsoft yahei font-size:></span></p></b.length>
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> b) {return 1;
    } else {return 0;
    }
  });  return inputArray.indexOf(newArray[1]);
};</inputarray.length>
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
          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></str.length>

较优解答为:

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools