Home Web Front-end JS Tutorial Share example tutorials for JavaScript exercises

Share example tutorials for JavaScript exercises

Jun 27, 2017 am 10:22 AM
javascript js tidy notes practise

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;
  });
}
Copy after login

The better answer is:

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

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]);
};
Copy after login
The better answer is:

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

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;
}
Copy after login

较优解答为:

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

分析:

这道题目就很简单了,较优解答中的扩展语法( 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;
    }
}
Copy after login

较优解答为:

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

分析:

较优解使用的是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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
How to delete Xiaohongshu notes How to delete Xiaohongshu notes Mar 21, 2024 pm 08:12 PM

How to delete Xiaohongshu notes? Notes can be edited in the Xiaohongshu APP. Most users don’t know how to delete Xiaohongshu notes. Next, the editor brings users pictures and texts on how to delete Xiaohongshu notes. Tutorial, interested users come and take a look! Xiaohongshu usage tutorial How to delete Xiaohongshu notes 1. First open the Xiaohongshu APP and enter the main page, select [Me] in the lower right corner to enter the special area; 2. Then in the My area, click on the note page shown in the picture below , select the note you want to delete; 3. Enter the note page, click [three dots] in the upper right corner; 4. Finally, the function bar will expand at the bottom, click [Delete] to complete.

How to practice typing with Kingsoft Typing Guide - How to practice typing with Kingsoft Typing Guide How to practice typing with Kingsoft Typing Guide - How to practice typing with Kingsoft Typing Guide Mar 18, 2024 pm 04:25 PM

Nowadays, many friends like to use Kingsoft Typing Assistant, but the typing speed seriously affects work efficiency, so I teach you to practice typing speed. So how to use Kingsoft Typing Assistant to practice typing? Today, the editor will give you a tutorial on how to practice typing numbers with Kingsoft Typing Assistant. The following is described, I hope it will be helpful to everyone. First, open the Kingsoft typing software, then click the (Getting Started) button with your mouse, then click the (Number Keys) button in a new window, then click the (Start from Scratch) button below to practice, or click the (Test Mode) button. , just enter numbers for practice. In addition, Kingsoft Typing Assistant has other functions that can help you practice typing better. 1. Select practice mode: On the software interface, you can see that there are different practice modes, such as &quot;New

What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? Mar 21, 2024 pm 09:30 PM

As a Xiaohongshu user, we have all encountered the situation where published notes suddenly disappeared, which is undoubtedly confusing and worrying. In this case, what should we do? This article will focus on the topic of &quot;What to do if the notes published by Xiaohongshu are missing&quot; and give you a detailed answer. 1. What should I do if the notes published by Xiaohongshu are missing? First, don't panic. If you find that your notes are missing, staying calm is key and don't panic. This may be caused by platform system failure or operational errors. Checking release records is easy. Just open the Xiaohongshu App and click &quot;Me&quot; → &quot;Publish&quot; → &quot;All Publications&quot; to view your own publishing records. Here you can easily find previously published notes. 3.Repost. If found

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu Mar 12, 2024 am 10:40 AM

How to add product links in notes in Xiaohongshu? In the Xiaohongshu app, users can not only browse various contents but also shop, so there is a lot of content about shopping recommendations and good product sharing in this app. If If you are an expert on this app, you can also share some shopping experiences, find merchants for cooperation, add links in notes, etc. Many people are willing to use this app for shopping, because it is not only convenient, but also has many Experts will make some recommendations. You can browse interesting content and see if there are any clothing products that suit you. Let’s take a look at how to add product links to notes! How to add product links to Xiaohongshu Notes Open the app on the desktop of your mobile phone. Click on the app homepage

See all articles