search
HomeWeb Front-endJS TutorialHow to analyze the usage of array types in classic js ability assessment questions_with code

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;
}

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); //删除时无需进行位移
        }
    }
}

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;
}

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;
}

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;
}

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;
    })
}

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;
}

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
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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools