Home  >  Article  >  Web Front-end  >  Explore 9 commonly used JavaScript functions with examples

Explore 9 commonly used JavaScript functions with examples

青灯夜游
青灯夜游forward
2022-10-09 19:23:572211browse

Explore 9 commonly used JavaScript functions with examples

Functions are one of the most important aspects of JavaScript. Without JavaScript functions, it would be very limited. Functions in javascript are used to perform specific operations or tasks.

They can be written in code or created using the Function constructor. Functions can be defined inside other functions, called nested functions. Nested functions can access the variables and parameters of the outer function.

This allows for some interesting and powerful programming techniques.

In this article, we will explore 9 commonly used javascript functions with examples.

1.filter

The filter function in JavaScript is used to filter out elements from an array based on specific conditions. In other words, the filter function will return a new array containing only those elements that satisfy the condition.

For example, if we have an array of numbers and we only want to get even numbers, we can use a filter function with a condition that checks even numbers.

Similarly, if we have an array of objects and we only want to get objects with a certain property value, we can use a filter function with a condition to check that property value. There are many other uses for the filter function.

filter example

let numbers = [15, 2, 50, 55, 90, 5, 4, 9, 10];
console.log(numbers.filter(number => number % 2 == 1));  // [15, 55, 5, 9]

2.forEach

Javascript foreach loop is a convenient tool for iterating arrays in JavaScript. It allows you to execute a specific set of code for each element in the array without writing a for loop. We'll look at how the foreach loop works and how you can use it in your own code.

We will discuss what kind of operations we can perform using forEach in JavaScript. JavaScript forEach is a looping construct that can be used in many programming languages, including JavaScript.

The main purpose of forEach is to allow programmers to iterate over a collection of data, such as an array or list.

To use JavaScript forEach, you first need an array. This can be created using the Array() constructor, or simply assigning a comma separated list of values ​​to a variable:

let myArray = [1,2,3];

Once you have your array you can start looping over it using the javaScript forEach example Iterate.

forEach example

    let text = "";
    const fruits = ["Apple", "Orange", "Cherry", "Banana"];
    fruits.forEach((item,index)=>{
        text += item +  ',' ; 
    });
    console.log(text)
    // Apple,Orange,Cherry,Banana,

3.map

Javascript The map function is a built-in method in JavaScript that allows you to Process each element in the array.

The map() method in JavaScript is used to transform elements in an array based on a function. The function is executed on each element of the array, with the element passed as argument.

The JavaScript map() method returns a new array containing the converted elements.

If you have an array of numbers and want to double them, you can use the map() method and a function that multiplies each number by 2.

In this case, the original array will not be modified. Instead, create a new array with double the value:

let arr = [1, 2, 3];
let newArr = arr.map(num => num * 2);
console.log(newArr)
//   1, 4, 9

Let’s look at another JavaScript map() example

const users = [
  {firstname : "Abhishek", lastname: "kumar"},
  {firstname : "jay", lastname: "sharma"},
  {firstname : "rupal", lastname: "sharma"}
];

users.map(getFullName);

function getFullName(item) {
  return [item.firstname,item.lastname].join(", ");
}

//  ['Abhishek, kumar', 'jay, sharma', 'rupal, sharma']

4.concat

Javascript String concatenation is the process of joining two or more strings together. The most common way to concatenate strings in javascript is using the operator. However, there are other ways to do this.

One way to concatenate strings in javascript is to use the = operator. This operator adds the string on the right side of the operator to the string on the left side of the operator. For example:

    let str1 = "Hello";
    let str2 = "World";
    str1 += str2; 
    console.log(str1) //Hello World

Another way to concatenate strings in javascript is to use the .concat() method.

js concat method is used to merge two or more strings together. This is useful if you want to build a single string out of multiple smaller strings.

The JavaScript concat() method does not change the existing string, but returns a new string containing the text of the combined strings.

concat example

const arr1 = ["Abhishek", "rupal"];
const arr2 = ["divya", "rahul", "harsh"];

const allUsers = arr1.concat(arr2);
//  Abhishek, rupal, divya, rahul, harsh

Concatenate three arrays:

const arr1 = ["Abhishek", "rupal"];
const arr2 = ["divya", "rahul", "harsh"];
const arr3 = ["kamal", "rohit"];

const allUsers = arr1.concat(arr2, arr3);
 
// Abhishek, rupal, divya, rahul, harsh, kamal, rohit

5.find

The find function can be a useful tool when working with arrays. This function will return the first element in the array that satisfies the given condition.

For example,

If we have an array of numbers and we want to find the first number greater than 5, we can use the find function. The JavaScript find function takes a callback as its first argument.

This callback is passed three parameters: the current element being processed, the index of the element, and the array itself.

If the element meets the condition, the callback should return true, otherwise it returns false. In our example, we will return true if the current element is greater than 5.

Javascript lookup capabilities are not limited to numbers. It can also be used with strings.

find example

const marks = [30, 70, 98, 77];

console.log(marks.find(checkMarks));

function checkMarks(mark) {
  return mark > 90;
}
//  98

find another example

const fruits = [
  { name: "apple", count: 10 },
  { name: "banana", count: 18 },
  { name: "mango", count: 3 }
];

const findMango = fruits.find(fruit =>fruit.name === "mango");

// { name: "mango", count: 3}

6.findIndex

When working with arrays, sometimes you may need to find the index of a specific element. This can be done using the JavaScript findIndex() method.

The JavaScript findIndex method returns the index of the first element in the array that satisfies the provided test function. Otherwise, it returns -1.

findindex JavaScript 方法类似于 JavaScript find 函数,但它返回索引而不是值。

findIndex() 函数有两个参数,一个回调函数和一个可选对象,该对象可用作回调函数中的 this 关键字。

findIndex示例

const marks = [30, 70, 98, 77];

console.log(marks.findIndex(checkMarks));

function checkMarks(mark) {
  return mark > 90;
}
//  2

findIndex 另一个例子

const fruits = [
  { name: "apple", count: 10 },
  { name: "banana", count: 18 },
  { name: "mango", count: 3 }
];

const findMango = fruits.findIndex(fruit =>fruit.name === "mango");
// 2

7.includes

JavaScript includes() 是一个内置函数,用于检查一个字符串是否包含另一个字符串。如果找到指定的字符串,则返回true,否则返回false。

JavaScript包含函数区分大小写,这意味着它将区分大小写字母,这意味着它将“Java”和“java”视为两个不同的字符串。

要检查 js 字符串是否包含另一个字符串,只需将要检查的字符串作为第一个参数传入,将要检查的字符串作为第二个参数传入。

例如,让我们检查字符串“Hello World”是否包含单词“world”。由于搜索区分大小写,因此将返回 false。

const birds = ["Birds", "peacock", "Dove", "Sparrow"];
console.log(birds.includes("Dove"));
// true

8.split

JavaScript中的split函数是一个String函数,用于将一个字符串拆分成一个子字符串数组,并返回新的数组。

原始字符串没有被修改。split 函数的语法是: split(str, separator, limit)

str - 要拆分的字符串。

separator – 用作分隔符的字符。如果省略,则使用单个空格 (' ') 作为分隔符。

limit -- 一个整数,指定要进行的拆分次数。如果省略,字符串将被拆分为一个没有限制的子字符串数组。

分隔符是一个字符串,它定义了应该在哪里拆分字符串。限制是一个整数,指定最大拆分数。

如果没有指定分隔符,字符串将被空白字符分割。如果未指定限制,则默认为 0,即没有限制。

Javascript split 函数的返回值是一个子字符串数组。如果字符串不能被拆分,它将返回一个空数组。

split示例

  let text = "Hello this is akashminds";
  console.log(text.split(" "));
  // ["Hello", "this", "is", "akashminds"];

另一个使用限制参数的 split示例

  let text = "Hello this is akashminds";
  console.log(text.split(" ", 3));
  // ["akashminds"];

9. substr

JavaScript substr 函数用于提取字符串的一部分。它有两个参数:开始位置和子字符串的长度。该函数返回一个新字符串,其中包含原始字符串的提取部分。

如果起始位置为负数,则从字符串的末尾开始计数。如果省略长度参数,JavaScript substr 会提取从字符串开始位置到结尾的所有字符。

javascript substr 函数可用于提取字符串的一部分或通过连接两个子字符串来创建新字符串。它还可以用于找出给定字符串中是否存在某个字符或子字符串。

const test = "Hey!, this is Akashminds, have a nice day ahead.";
console.log(test.substr(0, 30));

// Hey!, this is Akashminds, have

最后

您可以在日常使用中找到许多其他重要功能,但这些是我最常用的 9 个 JavaScript 功能。

作为用途最广泛、用途最广泛的编程语言之一,JavaScript 有着悠久的历史和光明的未来。在本文中,我们将通过示例探讨最常用的 9 个 JavaScript 函数。

在 JavaScript 中使用函数有很多优点。 首先,如果你有很多代码需要重用,把它放在一个函数中可以很容易地在你需要的时候再次调用它。

其次,使用函数可以通过将代码分解成更小的部分来帮助您提高代码的可读性。

这些是最常用的 9 个 JavaScript 函数以及示例。掌握这些功能将帮助你编写更好的代码,成为更精通的程序员。

【相关推荐:javascript视频教程编程基础视频

The above is the detailed content of Explore 9 commonly used JavaScript functions with examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete