Home Web Front-end JS Tutorial How to analyze the usage of array types in classic js ability assessment questions_with code

How to analyze the usage of array types in classic js ability assessment questions_with code

Jul 26, 2018 am 11:39 AM

I am currently working on a classic js ability assessment question, so I summarized it according to my own abilities and ideas. This article is mainly a summary of the array class.

1. Find the position of the element item in the given array: arr.indexOf(item);

2. Calculate the sum of all elements in the given array arr: arr .forEach(function(e){sum=sum e;})


Note: Array name.forEach(function(array element, element index, additionally defined array){function body}) / /What is returned is still the called array

Array name.map(function(array element){function body}) //What is returned is a new array, which does not modify the called array;

3. Remove the elements in the array arr whose ownership is equal to item. Do not modify the array arr directly. The result will be a new array.

function remove(arr, item) {
    var newArray=[];
    arr.forEach(function(e){
        if(e!=item){
            newArray.push(e);
        }
    })
    return newArray;
}
Copy after login

4. Remove all elements in the array arr that are equal to item, directly modify the given array, and return the result.

//方法一:从前往后遍历删除元素
function removeWithoutCopy(arr,item){
    for(i=0;i<arr.length;i++){
        if(item==arr[i]){
            arr.splice(i,1); //splice(定位元素索引[,删除元素个数,添加元素])
            i--;//i--的目的是因为删除了一个元素,在回到for时需要i++,会跳过一个元素
        }
    }
}

//方法二:从后往前遍历删除元素
function removeWithoutCopy(arr,item){
    for(i=arr.length-1;i>=0;i--){
        if(item==arr[i]){
            arr.splice(i,1); //删除时无需进行位移
        }
    }
}
Copy after login

Note: Array name.splice (index [, number, add elements]), splice means directly modifying the original array, and the return value is an array composed of deleted elements. Example: var a=[1,2,3,4,5];a.splice(3,1)//Return [4], a is [1,2,3,5]

5 , add the element item at the end of the array arr, do not modify arr directly, and return a new array.

//方法一:直接使用数组的concat追加新的item,并返回新的数组
function append(arr, item) {
    return arr.concat(item);
}

//方法二:利用slice对原数组进行切分,产生新的数组,在对新数组进行push即可
function append(arr, item) {
    var newArray=arr.slice(0);
    newArray.push(item);
    return newArray;
}
//方法三:利用数组的map创建新的数组,最后对新数组push(item)即可
function append(arr, item) {
    var newArray=arr.map(function(e){
        return e;
    })
    newArray.push(item);
    return newArray;
}
//方法四:定义一个空数组,利用for/forEach进行赋值,再对新数组push(item)即可
function append(arr, item) {
    var newArray=[];
    arr.forEach(function(e){
        newArray.push(e);
    })
    newArray.push(item);
    return newArray;
}
Copy after login

6. Delete the last element of array arr. Do not modify array arr directly. The result will be a new array: return arr.slice(0,arr.length-1);

7. Add element item at the beginning of array arr. Do not modify the array arr directly. The result will be a new array: var newArray=arr.slice(0);newArray.unshift(item)

8. Delete the first element of the array arr. Do not modify the array arr directly. The result is a new array: return arr.slice(1);

9. Merge array arr1 and array arr2. Do not modify the array arr directly. The result will be a new array: return arr1.concat(arr2);

10. Add the element item at the index of the array arr. Do not modify the array arr directly. The result is a new array: var newArray = arr.slice(0); newArray.splice(index,0,item); return newArray;

11. The median value of the statistical array arr is equal to The number of occurrences of item's elements.

function count(arr, item) {
    var count=0;
    arr.forEach(function(e){
        if(e==item)
            count+=1;
    });
    return count;
}
Copy after login

12. Find the repeated elements in the array arr. Input: [1, 2, 4, 4, 3, 3, 1, 5, 3]. Output: [1, 3, 4].

//方法一:利用indexOf和lastIndexOf进行判断
function duplicates(arr) {
    var result=[];
    arr.forEach(function(e){
        if(arr.indexOf(e)!=arr.lastIndexOf(e) && result.indexOf(e)==-1){
            result.push(e);
        }
    });
    return result;
}

//方法二:利用双重for循环进行判断
function duplicates(arr) {
    var result=[];
    for(i=0;i<arr.length-1;i++){
        for(k=0;k<result.length;k++){
            if(arr[i]==result[k])
                break;
        }
        if(k!=result.length) continue;
        for(j=i+1;j<arr.length;j++){
            if(arr[i]==arr[j]){
                result.push(arr[i]);
                break;
            }
        }
    }
    return result;
}
Copy after login

13. Find the second power of each element in the array arr. Do not modify the array arr directly, the result will be a new array.

//方法一:定义空数组,对arr进行遍历赋值
function square(arr) {
    var newArr=[];
    arr.forEach(function(e){
        newArr.push(e*e);
    });
    return newArr;
}
//方法二:直接使用map产生新的数组
function square(arr) {
    return arr.map(function(e){
        return e*e;
    })
}
Copy after login

14. In the array arr, find all positions where the element whose value is equal to item appears

function findAllOccurrences(arr, target) {
    var newArray=[];
    arr.forEach(function(e,i){
        if(e==target) newArray.push(i);
    })
    return newArray;
}
Copy after login

In the classic js questions, the above is the question type of all arrays, and then the following is It is a coding specification and function module.

Related recommendations:

BootStrap classic case analysis

PHP string operation classic introduction

Video tutorial: 27 classic practical exercises for front-end JS development

The above is the detailed content of How to analyze the usage of array types in classic js ability assessment questions_with code. 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles