TypeError:无法从未定义读取属性长度
我有两个字符串,这些字符串可能不确定或定义一些值。
var a ; // [Array of strings]
var b ; // [Array of strings]
var c; // result array
我需要在第三个数组中的第三个数组中的“ ABC”等静态值,如var c 定义数组A或数组B及其长度> 0。但是我的脚本正在打破,这是下面的代码行。
if((typeof a !== 'undefined' ||typeof b !== 'undefined' ) && (a.length > 0 || b.length > 0) )
当我为“ A”分配一些值时,上述LOC失败了。错误日志向我显示以下。
by: javax.script.ScriptException: TypeError: Cannot read property \"length\" from undefined\n\tat
我该如何将这种条件更改为满足我的要求。还有更好的选择。
I am having two arrays of strings which may be undefined or defined with some value.
var a ; // [Array of strings]
var b ; // [Array of strings]
var c; // result array
I need to push some static value like "abc" in a third array like var c whenever either of the
array a or array b are defined and their length > 0. But my script is breaking , this is the line of code below.
if((typeof a !== 'undefined' ||typeof b !== 'undefined' ) && (a.length > 0 || b.length > 0) )
The above loc fails when I am assigning some value to 'a' and b is undefined. Error logs show me the below.
by: javax.script.ScriptException: TypeError: Cannot read property \"length\" from undefined\n\tat
How can I change this condition to satisy my requirements.Is there a better away to achieve this.Also, I am using Rhino JS engine 1.13 ver.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以重写它,例如
确保仅在每个变量不确定时才检查它们的长度。
顺便说一句,如果您使用
'使用严格'
模式,则只需使用a!== undefined
而不是type> type a!=='undefined''
。You could rewrite it like
To ensure you only check the length of each variable only if they are not undefined.
By the way, if you are using
'use strict'
mode, you can just usea !== undefined
instead oftypeof a !== 'undefined'
.我在您的代码中看到的问题是第一个评估,
当
a
或b
是'undefined'
时,它将返回true。例如,想象一个实例,其中
a
未定义,但是b
是一个数组。(type a!=='undefined'||类型B!=='undefined')
评估true
。使用或(
||
)操作的第二个评估,从左到右开始;首先评估
但
a
是'undefined'
,因此是错误。我会用这个
The problem I see in your code is the first evaluation
It returns true when either
a
orb
is'undefined'
.For instance, imagine an instance where
a
is undefined butb
is an array;(typeof a !== 'undefined' ||typeof b !== 'undefined' )
evaluates totrue
.The second evaluation which uses an OR (
||
) operation which starts from left to right;starts by evaluating
but
a
is'undefined'
and hence the error.I would use this
在JavaScript中,您还可以检查该变量的值是无效的还是未定义的。
我想这会帮助您。尝试以下操作:
In Javascript, you can also check whether the value of the variable is null or undefined with the below way.
I guess this will help you. Try this:
您应将
组分组
测试,然后组b
测试。并且,当犀牛支持
array.isarray()
时,这是一个较小且清洁的代码:You should group
a
tests then groupb
tests.And, as Rhino supports
Array.isArray()
, here is a smaller and cleaner code: