我有兩個字串陣列,它們可能未定義或定義了一些值。
var a ; // [Array of strings]
var b ; // [Array of strings]
var c; // result array
每當定義了陣列 a 或陣列 b 并且它們的長度 > 0 時,我需要在第三個陣列(如 var c)中推送一些靜態值(如“abc”)。但我的腳本正在中斷,這是下面的代碼行。
if((typeof a !== 'undefined' ||typeof b !== 'undefined' ) && (a.length > 0 || b.length > 0) )
當我為 'a' 分配一些值并且 b 未定義時,上述 loc 失敗。錯誤日志向我顯示以下內容。
by: javax.script.ScriptException: TypeError: Cannot read property \"length\" from undefined\n\tat
我怎樣才能改變這個條件來滿足我的要求。有沒有更好的方法來實作這個。另外,我使用的是 Rhino JS 引擎 1.13 版本。
uj5u.com熱心網友回復:
你可以像這樣重寫它
if((a !== undefined && a.length > 0) || (b !== undefined && b.length > 0)) {
c = ...
}
以確保僅在每個變數未定義時才檢查它們的長度。
順便說一句,如果您使用的是'use strict'模式,您可以使用a !== undefined代替typeof a !== 'undefined'.
uj5u.com熱心網友回復:
您應該a對測驗進行分組,然后對測驗進行分組b。
if (
a !== "undefined" && a.length && a.length > 0
|| b !== "undefined" && b.length && b.length > 0
) {
c.push("abc");
}
如果 Rhino 支持Array.isArray(),這里有一個更小的代碼:
if (Array.isArray(a) && a.length > 0 || Array.isArray(b) && b.length > 0) {
c.push("abc");
}
它在 Rhino JS 引擎中作業嗎?
uj5u.com熱心網友回復:
我在您的代碼中看到的問題是第一次評估
(typeof a !== 'undefined' ||typeof b !== 'undefined' )
a當orb為時,它回傳 true 'undefined'。例如,想象一個a未定義但b為陣列的實體;(typeof a !== 'undefined' ||typeof b !== 'undefined' )評估為true。
使用從左到右開始的OR ( ) 操作的第二次評估;||
(a.length > 0 || b.length > 0)
從評估開始
a.length
但是a是'undefined',因此是錯誤。
我會用這個
if((a !== undefined && a.length > 0) || (b !== undefined && b.length > 0)) {
// Do something
}
uj5u.com熱心網友回復:
在 Javascript 中,您還可以通過以下方式檢查變數的值是 null 還是 undefined。
我想這會對你有所幫助。試試這個:
if(a?.length > 0 && b?.length > 0){
// Code here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478927.html
