简体   繁体   English

JavaScript中的严格模式限制

[英]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. 我的程序必须完美地通过JSLint,这意味着我需要在严格模式下使用函数。 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. 我现在仅将它们置于严格模式下,这意味着我以后尝试调用我在SepNsLs函数中声明并填充的letterArray和numberArray的函数不再调用那些数组,并且这些数组未声明。 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. 如您所见,我在addNumbers函数中调用sepNsLs函数,但是由于严格的模式,我无法使用sepNsLs创建的数组。 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? 此外,是否有像javascript beautifier这样的网站可以修复我当前的代码以符合严格的模式约定?

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. splitterSpacerator可以这样,如果我选择在一个空格处分割输入字符串,则告诉我的程序在空格处分割的输入框会声明“ Space”一词,因此我可以看到它是一个空格,我正在将字符串分割为。

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. 当您尝试在addNumbers内部访问numberArray ,该numberArray不存在。

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. 更好的选择是#2,因为实际上不会用变量污染全局范围。 And you can declare "use strict" at the top of the outer function and it will force everything in it into strict mode. 您可以在外部函数的顶部声明"use strict" ,它将强制其中的所有内容进入严格模式。

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. 我不能使用sepNsLs创建的数组。 How do I fix this? 我该如何解决?

One way of fixing this would be to return arrays sepNsLs creates with eg a tuple - return [numberArray, letterArray]; 解决此问题的一种方法是返回sepNsLs用例如元组创建的数组-return return [numberArray, letterArray]; , and then use it like: ,然后像这样使用它:

a) es6 syntax: a)es6语法:

var [numberArray, letterArray] = sepNsLs();

b) pre-es6 syntax: b)ES6之前的语法:

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. addNumbers功能也应该可能返回sum -否则,因为它代表它不产生任何有意义的结果。

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). 变量letterArraynumberArray声明为函数sepNsLs局部变量,仅在该范围内访问(无论是否严格模式)。 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: 范例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). 您需要做的是对变量letterArraynumberArray ,以使sepNsLsaddNumbers (在它们两者sepNsLs一个作用域)都可以访问它们。 Or return the value from sepNsLs and store it in a variable inside addNumbers . 或从sepNsLs返回值并将其存储在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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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