簡體   English   中英

使用參數通過 function 調用 for 循環

[英]call for loop through function with parameters

我有以下 for 循環,我在我的代碼中有很多次,具有不同的變量名稱,我會將它放在帶有參數的 function 中並調用它,但它不起作用

 for(let i = 0; i < inputs.length - 1; i++){ if(.nputs[i].value){ error += inputs[i];getAttribute('test') + " is blank"; isTrue = false; } }

這是我所做的

 let y = ""; let z = true; function test(x,y,z){ for(let i = 0; i < x.length - 1; i++){ if(.x[i].value){ y += x[i];getAttribute('name') + " is blank;"; z = false; } } } let error = "", let isTrue = true, test(inputs;error,isTrue);

我應該返回 function 嗎? 如果是,我應該做哪個退貨?

  1. Scope : when you define y and z outside the function (in the global scope presumably) they are different than the y and z defined in the parameter list of the function. 參數列表中的僅存在於 function 的主體中。 更改 function 中名為y參數的值不會更改全局變量y的值。 所以對你的問題的簡單回答是,是的,你需要返回一些東西,因為當 function 完成執行時,參數y的值會丟失。

  2. 給你的變量起描述性的名字。 讓混淆器稍后再做。

function test(x,y,z) -> function valueTest(arr, err, success)

  1. boolean 狀態和錯誤字符串是信息的冗余位。 如果錯誤字符串不為空,則狀態為失敗。 因此,您不需要同時返回 boolean 和字符串。

  2. 上一個測試的狀態與下一個測試無關。 Therefore, z or success doesn't have to be passed in to the function each time, as it (or something like it) is really the desired output of the function, and each call of the function can be treated separately. 如果您想組合來自不同測試的結果,那么這應該是調用此 function 的任何問題 - 請參閱關注點分離耦合

function 實際需要的唯一參數是被測值(數組)。

  1. 當您編寫 function 時,您定義了返回值,因此您定義了其他代碼如何破譯這些結果。 function 本身不必完成解釋結果和構建錯誤字符串的所有工作。 如果您的返回值只是一個name屬性值數組(測試數組中失敗的元素),則調用代碼仍然可以處理“成功”或“失敗”。 如果返回值包含一個或多個元素,或者length > 0 ,則表示失敗。

刪除冗余/不必要的參數和信息,您將擁有一個看起來像這樣的 function:

function valueTest(arr) {
    let results = [];

    for (let i = 0; i < arr.length - 1; i++){
        if (!arr[i].value) {
            results.push(arr[i].getAttribute('name'));
        }
    }

    return results;
}

調用者可以從中破譯並構建錯誤消息。 function 通過返回<name> is blank! 而不僅僅是<name> ,然后你只需要加入數組的元素。

...so within the function...

results.push(arr[i].getAttribute('name') + ' is blank!');

...and back in the global scope...

const error = valueTest(inputs).join(" ");
let success = error.length > 0;

5.如果您想要來自不同測試的運行狀態指示器,請評估單個測試的結果,然后將其與之前的結果進行logically AND

const result1 = valueTest(inputs1).join(' ');
let success = results1.length > 0;
const result2 = valueTest(inputs2).join(' ');
success &= (results2.length > 0);

看到您的代碼問題已在評論中處理,我向您介紹了一種更簡單的方法。

如果您計算具有該屬性且不為空的元素並將其與通過的所有輸入的長度進行比較,您將獲得更好的測試

const test = (inputs,attr) => [...inputs]
  .filter(inp => inp.getAttribute(attr) && inp.value.trim() !== "").length === inputs.length;

const istrue = test(document.querySelectorAll("input"),"name")

如果所有傳遞的輸入都有一個名為 name 的屬性,isTrue 將為真

你也可以做

const elems  = document.querySelectorAll("input[name]")
const isTrue = elems.filter(inp => inp.value.trim() !== "").length === elems.length

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM