search
HomeWeb Front-endJS TutorialShare a basic script algorithm example

Share a basic script algorithm example

Jun 23, 2017 am 09:51 AM
primarychallengealgorithmprogrammingScript

之前偶然看到了w3c上的编程挑战题,就像拿来试试手,先做的是初级脚本算法,总体不难,如果有更好的方法,希望能一起交流!

1、翻转字符串

先把字符串转化成数组,再借助数组的reverse方法翻转数组顺序,最后把数组转化成字符串。

        function reverseString(str) {var str2 = '';for(var i=str.length-1;i>=0;i--){
                str2 += str[i];
            }return str2;
        }function reverseString(str){var strArray = str.split('');
            strArray.reverse();
            str = strArray.join('');return str
        }

 

2、计算一个整数的阶乘

如果用字母n来代表一个整数,阶乘代表着所有小于或等于n的整数的乘积。

        function factorialize(num) {var sum = 1;for(var i=num;i>0;i--){
                sum *= i;
            }

            console.log(sum);return sum;
        }function factorialize(num) {if(num ==1){return 1;
            }else{return arguments.callee(num-1)*num;
            }

        }

 

3、回文算法

如果给定的字符串是回文,返回true,反之,返回false

如果一个字符串忽略标点符号、大小写和空格,正着读和反着读一模一样,那么这个字符串就是(回文)。

注意你需要去掉字符串多余的标点符号和空格,然后把字符串转化成小写来验证此字符串是否为回文。

            function palindrome(str) {var arr = [];
                str = str.toLowerCase();                for(var i=0;i<str.length>=97) || 
                    (str.charCodeAt(i)=48)){
                        arr.push(str[i]);
                    }
                }//只需要判断数组一半的次数就全部比较完了,不必再浪费时间了for(var i=0;i<math.ceil>|\/|\?]/g,"");

                str1 = str.split('');
                str1.reverse();
                str2 = str1.join('');if(str === str2){return true}else{return false;
                }


            }</math.ceil></str.length>

 

4、寻找最长的单词算法

找到提供的句子中最长的单词,并计算它的长度。

函数的返回值应该是一个数字。

        // 利用charCodeAt()方法判断是不是一个单词,并记录单词长度,最后获得最长的单词长度function findLongestWord(str) {var num = 0,
                max = 0;for (var i = 0; i  max ? num : max;
                    num = 0;
                }
            }// 比较最后一个单词的长度max = num > max ? num : max;return max;
        }// 利用split()方法将字符串分成每个单词组成的数组,取得其中最长的长度function findLongestWord(str){           var max = 0;           var arr = str.split(' ');           for(var i=0;i<arr.length>max?arr[i].length:max;
           }           return max;

        }</arr.length>

 

5、设置首字母大写算法

确保字符串的每个单词首字母都大写,其余部分小写。

像'the'和'of'这样的连接符同理。

        //将字符串用split()方法转为数组,并用数组中的每个项的首字母的大写和这个项剩余的字符拼接,最后转为字符串function titleCase(str) {var arr,upChar;
            str = str.toLowerCase();
            arr = str.split(' ');            for(var i=0;i<arr.length></arr.length>

 

6、寻找数组中的最大值算法

右边大数组中包含了4个小数组,分别找到每个小数组中的最大值,然后把它们串联起来,形成一个新数组。

        function largestOfFour(arr) {var max = 0,
                result = [];for(var i=0;i<arr.length>max?n:max;
                }
                result.push(max);
                max = 0;
            }return result;
        }</arr.length>

 

7、确认末尾字符算法

检查一个字符串(str)是否以指定的字符串(target)结尾。

如果是,返回true;如果不是,返回false。

        // 从后开始比较function confirmEnding(str, target) {for (var i = 0; i 

 

8、重复操作算法

重要的事情说3遍!

重复一个指定的字符串 num次,如果num是一个负数则返回一个空字符串。

        function repeat(str, num) {var result = '';if(num

 

9、字符串截取算法

用瑞兹来截断对面的退路!

截断一个字符串!

如果字符串的长度比指定的参数num长,则把多余的部分用...来表示。

切记,插入到字符串尾部的三个点号也会计入字符串的长度。

但是,如果指定的参数num小于或等于3,则添加的三个点号不会计入字符串的长度。

        function truncate(str, num) {var result = '';var strArr = str.split('');if(numnum){
                result = str.slice(0,num-3) + '...';
            }else{
                result = str;
            }return result;
        }

 

10、数组分割算法

猴子吃香蕉可是掰成好几段来吃哦!

把一个数组arr按照指定的数组大小size分割成若干个数组块。

        function chunk(arr, size) {var result = [];var a = [];for(var i=0;i<arr.length></arr.length>

 

11、数组截断算法

打不死的小强!

返回一个数组被截断n个元素后还剩余的元素,截断从索引0开始。

        function slasher(arr, howMany) {           var result = [];           for(var i=howMany;i<arr.length></arr.length>

 

12、数组查询算法

蛤蟆可以吃队友,也可以吃对手。

如果数组第一个字符串元素包含了第二个字符串元素的所有字符,函数返回true。

举例,["hello", "Hello"]应该返回true,因为在忽略大小写的情况下,第二个字符串的所有字符都可以在第一个字符串找到。

["hello", "hey"]应该返回false,因为字符串"hello"并不包含字符"y"。

["Alien", "line"]应该返回true,因为"line"中所有字符都可以在"Alien"找到。

    function mutation(arr) {var arr1 = arr[0].toLowerCase();
        console.log(arr1)var arr2 = arr[1].toLowerCase();for(var i=0;i<arr></arr>

 

13、删除数组中特定值

真假美猴王!

删除数组中的所有假值。

在JavaScript中,假值有falsenull0""undefined 和 NaN

       function bouncer(arr) {// Don't show a false ID to this bouncer.for(var i=0;i<arr.length></arr.length>

 

14、去除数组中任意多个值

金克斯的迫击炮!

实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的值。

        function destroyer(arr) {// Remove all the valuesvar arr = arguments[0];
            console.log(arr[1]);var data = Array.prototype.slice.call(arguments,1);for(var j=0;j<data.length></data.length>

 

15、数组排序并插入值

我身在何处?

先给数组排序,然后找到指定的值在数组的位置,最后返回位置对应的索引。

举例:where([1,2,3,4], 1.5) 应该返回 1。因为1.5插入到数组[1,2,3,4]后变成[1,1.5,2,3,4],而1.5对应的索引值就是1

同理,where([20,3,5], 19) 应该返回 2。因为数组会先排序为 [3,5,20]19插入到数组[3,5,20]后变成[3,5,19,20],而19对应的索引值就是2

        function where(arr, num) {
            arr.sort(function(a,b){return a - b;
            });for(var i=0;i<arr.length> arr[i] && num arr[arr.length-1]){return arr.length;
                }

            }

        }</arr.length>

 

16、位移密码算法

让上帝的归上帝,凯撒的归凯撒。

下面我们来介绍风靡全球的凯撒密码Caesar cipher,又叫移位密码。

移位密码也就是密码中的字母会按照指定的数量来做移位。

一个常见的案例就是ROT13密码,字母会移位13个位置。由'A' ↔ 'N', 'B' ↔'O',以此类推。

写一个ROT13函数,实现输入加密字符串,输出解密字符串。

所有的字母都是大写,不要转化任何非字母形式的字符(例如:空格,标点符号),遇到这些特殊字符,跳过它们。

            function rot13(str) { // LBH QVQ VG!var result = [];for(var i=0;i<str.length>= 65 && str.charCodeAt(i) 90){
                            code = str.charCodeAt(i) + 13 - 26;
                        }
                        
                        result.push(String.fromCharCode(code));
                    }else{
                        result.push(str[i]);
                    }
                }return result.join("");
            }</str.length>

 

The above is the detailed content of Share a basic script algorithm example. 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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor