警报打印数组怎么样,虽然需要字符串?

时间:2016-12-01 19:07:55

标签: javascript arrays

我是javascript的初学者,我有一个问题,我有一个类似

的数组
class Program
{
    static void Main(string[] args)
    {
        DateTime dUtc = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Utc);
        DateTime dUnspecified = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Unspecified);

        //Sample of an unintended mangle:
        //Prints "2016-06-01 10:17:00Z"
        Console.WriteLine(dUnspecified.ToUniversalTime().ToString("u"));

        //Prints "2016 - 06 - 01 03:17:00Z"
        Console.WriteLine(dUtc.SafeUniversal().ToString("u"));

        //Prints "2016 - 06 - 01 03:17:00Z"
        Console.WriteLine(dUnspecified.SafeUniversal().ToString("u"));
    }
}

public static class ConvertExtensions
{
    public static DateTime SafeUniversal(this DateTime inTime)
    {
        return (DateTimeKind.Unspecified == inTime.Kind)
            ? new DateTime(inTime.Ticks, DateTimeKind.Utc)
            : inTime.ToUniversalTime();
    }
}

为什么alert或innerhtml会正确显示结果,尽管它是一个数组,而不是一个字符串? 我认为在其他编程技术中应该触发错误,并且消息告诉我们这是一个不允许转换的字符串数组。

3 个答案:

答案 0 :(得分:0)

使用对象值调用alert时(数组是对象,只是特殊情况),它会自动调用该值的toString

var arr = [1, 2, 3];
// Notice that they show the same result
alert(arr);
alert(arr.toString());

关于Javascript的事情是它是用类型强制动态键入的。在外行人看来,这意味着它将自动尝试将数据转换为给定上下文的正确类型。例如:

// Converts the number to a string
console.log(1 + '2');

// Converts the booleans values to numbers
console.log(true + true);

答案 1 :(得分:0)

我认为javascript中的Alert会将您的数组解析为字符串以显示它,这就是原因。如果您想知道对象的类型,请使用typeof

如果您有JSON,并希望将其打印为字符串,请使用JSON.stringify

答案 2 :(得分:0)

由于javascripts接受使用默认.toString()方法显示的字符串数组,因此不会抛出错误。如果你想处理catch错误,请使用try catch这样

var nameOfName=["john","mark"];
try{
document.getElementById("anyelementid").innerHTML=nameOfName;
  }
catch(ex){
document.getElementById("anyelementid").innerHTML=ex.message;
  }
<div id="anyelementid"></div>