简体   繁体   中英

Strict mode constrictions in Javascript

Hey so I have a function that takes a string from an input box and splits it up to numbers and letters, seen here:

function sepNsLs() {
  "use strict"; 
  var letterArray = [];
  var numberArray = [];
  separatorSpacerator();
  var L = 0;
  var listResult = document.getElementById("listInput").value;
  var splitResult = listResult.split(separator.sep);
  for (; L < splitResult.length; L++) {
    if (isNaN(splitResult[L])) {
      letterArray.push(splitResult[L]);
    } else if (Number(splitResult[L])) {
      numberArray.push(splitResult[L]);
    }
  }
}

My program has to pass through JSLint perfectly, meaning I need to use my functions in strict mode. I've only put them in strict mode now, meaning that my later functions that try to call the letterArray and numberArray that I declared and filled in the SepNsLs function no longer call those arrays and the arrays come up undeclared. Here's the code for one of them:

function addNumbers() {
  "use strict"; 
  var sum = 0;
  var i = 0;
  sepNsLs();
  while (i < numberArray.length) {
    sum = sum + Number(numberArray[i]);
    i++;
  }

As you can see, I call the sepNsLs function in the addNumbers function, but because of strict mode, I can't use the arrays sepNsLs creates. How do I fix this? Also, is there a website like the javascript beautifier that will fix my current code to fit strict mode conventions?

EDIT: Separator is declared a global variable here:

var separator = {
  sep: 0
};

separatorSpacerator makes it so that if I choose to split my input strings at a space, the input box to tell my program to split at the spaces declares the word "Space" so I can see it is a space I'm splitting my string at.

function separatorSpacerator() {
  "use strict"; 
  var list = document.getElementById("listInput").value;
  if (document.getElementById("separatorInput").value === "space") {
    separator.sep = " ";
  } else if (document.getElementById("separatorInput").value === " ") {
    separator.sep = " ";
    document.getElementById("separatorInput").value = "space";
  } else {
    separator.sep = document.getElementById("separatorInput").value;
  }
  if (list.indexOf(separator.sep) === -1) {
    alert("Separator not found in list!");
    clearResults();
  }
}

Your problem is one of scope. When you try to access numberArray inside of addNumbers it doesn't exist.

You have a couple of options:

  1. Make all the variables that need to be accessed in each function global.
  2. Wrap all of your functions in an outer function and place the 'global' variables into that outer scope.

The better option is #2, because you won't actually be polluting the global scope with variables. And you can declare "use strict" at the top of the outer function and it will force everything in it into strict mode.

Something like this:

(function() {
    "use strict";

    // These are now in-scope for all the inner functions, unless redclared
    var letterArray = [], numberArray = [], separator = {sep: 0};

    function sepNsLs() {
       // code goes here
    }
    function addNumbers(){ 
       // code goes here
    }
    function separatorSpacerator(){ 
       //code goes here
    }
    // ...more functions and stuff

    // and then call...
    theFunctionThatKicksOffTheWholeProgram();

}());

I can't use the arrays sepNsLs creates. How do I fix this?

One way of fixing this would be to return arrays sepNsLs creates with eg a tuple - return [numberArray, letterArray]; , and then use it like:

a) es6 syntax:

var [numberArray, letterArray] = sepNsLs();

b) pre-es6 syntax:

var split = sepNsLs(),
    numberArray = split[0],
    letterArray = split[1];

Your addNumbers function should also probably return sum - otherwise, it doesn't produce any meaningful results as it stands.

Although not relevant to the question and is more of a matter of naming convention preference - you might want to explore on Hungarian notation and its' drawbacks.

The variables letterArray and numberArray are declared local to the function sepNsLs , they are only accessed in that scope (strict mode or not). Here is an example:

 function foo() { var fooVar = 5; console.log(fooVar); }// fooVar get destroyed here function bar() { console.log(fooVar); // undefined because fooVar is not defined } foo(); bar(); 

A scope usually is from an open brace { to it's matching close brace } . Any thing declared inside a scope is only used withing that scope. Example 2:

 var globalVar = 5; // belongs to the global scope function foo() { var fooVar = 6; // belongs to the foo scope function bar1() { console.log(globalVar); // will look if there is a globalVar inside the scope of bar1, if not it will look if there is globalVar in the upper scope (foo's scope), if not it will in the global scope. console.log(fooVar); // same here var bar1Var = 7; // belongs to bar1 scope } function bar2() { var globalVar = 9; // belongs to the bar2 scope (shadows the global globalVar but not overriding it) console.log(globalVar); // will look if there is a globalVar in this scope, if not it will look in one-up scope (foo's scope) .... untill the global scope console.log(bar1Var); // undefined because bar1Var doesn't belong to this scope, neither to foo's scope nor to the global scope } bar1(); bar2(); console.log(globalVar); // prints 5 not 9 because the serach will be in foo's and the global scope in that order } foo(); 

What you need to do is to decalre the variables letterArray and numberArray where they can be access by both sepNsLs and addNumbers (one scope above both of them). Or return the value from sepNsLs and store it in a variable inside addNumbers . Like this:

function sepNsLs() {

  // logic here

  return numberArray; // return the array to be used inside addNumbers
}

function addNumbers() {

  var arr = sepNsLs(); // store the returned value inside arr

  for(var i = 0; i < arr.length; ... // work with arr

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM