奇怪的Javascript结果

奇怪的Javascript结果,javascript,json,parsing,null,undefined,Javascript,Json,Parsing,Null,Undefined,为什么这段代码会返回-null-,而据我理解,它应该返回-,它似乎将null视为字符串 var testvar = null; alert(" - "+testvar+" - "); 就这样。未定义的也是如此。我需要这样做,因为我有一个数组,我在数组中一个接一个地循环,并将每个项添加到一个变量中,该变量是一个字符串 我有这个: //'resp' variable is a JSON response, decoded with JSON.parse. This part works fine

为什么这段代码会返回
-null-
,而据我理解,它应该返回
-
,它似乎将
null
视为字符串

var testvar = null;
alert(" - "+testvar+" - ");
就这样。未定义的
也是如此。我需要这样做,因为我有一个数组,我在数组中一个接一个地循环,并将每个项添加到一个变量中,该变量是一个字符串

我有这个:

//'resp' variable is a JSON response, decoded with JSON.parse.  This part works fine.
var addOnEnd=null;
for (item in resp) {
    console.log(">"+item);
    addOnEnd += item+"\n";
}
log读取我期望的内容—响应中所有项的列表

但是,如果我在for循环之后发出警报(
addoned
),它将返回“undefined”(字面上是字符串),然后返回数组的其余部分

我做错了什么?

将其更改为:

alert(“-”+(testvar | |)”)+“-”

…还有这个

addOnEnd+=(项| |“”)+“\n”

您还需要将addOnEnd初始化为空字符串,而不是null。

这样,如果该值未定义(当作为布尔值计算时返回false),它将使用空字符串的“默认”值。

将其更改为:

alert(“-”+(testvar | |)”)+“-”

…还有这个

addOnEnd+=(项| |“”)+“\n”

您还需要将addOnEnd初始化为空字符串,而不是null。


这样,如果该值未定义(当作为布尔值计算时返回false),它将使用空字符串的“默认”值。

结果是正确的。您将看到
toString
null
undefined

如果要替换空字符串,请执行该操作

var testvar = null;
alert(" - "+ (testvar == null ? "" : testvar) +" - ");


结果是正确的。您将看到
toString
null
undefined

如果要替换空字符串,请执行该操作

var testvar = null;
alert(" - "+ (testvar == null ? "" : testvar) +" - ");


当链接(添加)到字符串时,null值被强制为字符串“null”。 你想要的是这个

var addOnEnd="";
for (item in resp) {
    console.log(">"+item);
    addOnEnd += item +"\n";
}

当链接(添加)到字符串时,null值被强制为字符串“null”。 你想要的是这个

var addOnEnd="";
for (item in resp) {
    console.log(">"+item);
    addOnEnd += item +"\n";
}

我怀疑问题出在你的数据上

var testvar = null;
alert(" - "+testvar+" - ");
// RESULT "- null -" --> as expected.  

var addOnEnd=null;
for (item in {key: "val1", key2: "val2"}) {
  console.log(">"+item);
   addOnEnd += item+"\n"; 
}
alert(addOnEnd)
//result (nullKey1\nKey2)

我怀疑问题出在你的数据上

var testvar = null;
alert(" - "+testvar+" - ");
// RESULT "- null -" --> as expected.  

var addOnEnd=null;
for (item in {key: "val1", key2: "val2"}) {
  console.log(">"+item);
   addOnEnd += item+"\n"; 
}
alert(addOnEnd)
//result (nullKey1\nKey2)

谢谢alert()代码段适用于第一个示例,但第二个示例不适用,这很奇怪,因为它基本上是同一个代码
addOnEnd='',更新了我的答案:)看起来像是@Theodore发现的-我没有:)谢谢!!我知道这很简单。我一直在跳Around PHP、HTML、CSS、MySQL(I)和JS/jQuery,所以我没有完全关注一种语言的工作方式。再次感谢!谢谢alert()代码段适用于第一个示例,但第二个示例不适用,这很奇怪,因为它基本上是同一个代码
addOnEnd='',更新了我的答案:)看起来像是@Theodore发现的-我没有:)谢谢!!我知道这很简单。我一直在跳Around PHP、HTML、CSS、MySQL(I)和JS/jQuery,所以我没有完全关注一种语言的工作方式。再次感谢!只是尝试了一下,不幸的是同样的结果。我尝试了您的示例数据,脚本返回了
nullkey2
@Jaxo——这就是它/应该/返回的内容。根据您的问题,它返回
undefined
,后跟键值。我设置了我的示例来显示它应该返回
null
,而不是
undefined
。如果您希望去掉
null
,请执行以下操作:
var addoned=“”取而代之。只是尝试了一下,不幸的是同样的结果。我尝试了您的示例数据,脚本返回了
nullkey2
@Jaxo——这就是它/应该/返回的内容。根据您的问题,它返回
undefined
,后跟键值。我设置了我的示例来显示它应该返回
null
,而不是
undefined
。如果您希望去掉
null
,请执行以下操作:
var addoned=“”取而代之。