1

When I was learning javascript, I found a practice problem (below)

Write a JavaScript program to check whether a string "Script" presents at 5th (index 4) position in a given string, if "Script" presents in the string return the string without "Script" otherwise return the original one.

This is my code below:

        function string_check(str) {
            arr=str.split("");
            if(arr.splice(4,6).join("")=="Script"){
                arr.splice(4,6);
                str=arr.join("");
                return str;
            }else{
                return str;
            }

        }
        console.log(string_check("javaScriptpython"));

This code outputs'java 'on the console, which is not what I want, so I change - delete' arr.splice (4,6); ', the console outputs the correct answer。 So I guess the judgment condition in the'if' judgment statement is not only used for judgment, but also for execution.

So I changed the code to the following to prove my idea

    <script>
        function string_check(str) {
            arr = str.split("");
            console.log(window.arr);
            if (arr.splice(4, 6).join("") == "Script") {
                console.log(window.arr);
                str = arr.join("");
                return str;
            } else {
                return str;
            }
        }
        console.log(string_check("javaScriptpython"));
    </script>

But the console output: output This makes me even more confused as a beginner,It seems to me that the first 'console.log (window.arr) 'should output an array of length 16, but it outputs an array of length 10

yoga
  • 23
  • 5
  • You're spliting string to array `str.split(" ");` and logging `arr` try to log `str` – Dreamy Player Nov 16 '22 at 11:00
  • Your second code snippet works fine, no? What is confusing about it? It outputs "javapython" at the bottom. – Ivar Nov 16 '22 at 11:04
  • You are using non-standard terminology in your question and I don't think anyone actually understand your question (judging by the "duplicate" which very clearly has **absolutely nothing to do with the question** if I understand you correctly). What do you mean by `judgement`? – slebetman Nov 16 '22 at 12:00

0 Answers0