反正知道javascript变量的具体类型

时间:2016-07-09 16:52:50

标签: javascript arrays object

我的变量data低于

var data = [
{
    id: 1,
    name: "John",
    sex: "M",
    maritalStatus: "M",
    dob:"01-01-1990",
    title:"Software Engineer",
    address:"VN",
    phoneNumber:"(123) 456-7890",
    email: "john@gmail.com"
}
];

var data = [
    ["1", "John", "M", "M", "1990", "Software Engineer", "john@gmail.com", "(123) 456-7890"],
];

无论如何都知道他们的类型。我使用typeof(data)但都显示了它的对象。

2 个答案:

答案 0 :(得分:0)

Array.isArray(data)将返回true,因为数据是一个数组。

修改

在回答的评论中澄清后,Array.isArray(data[0])将检查数组数据中的第一个元素是否为数组。

答案 1 :(得分:0)

你可以使用Object.prototype.toString()。call(object)

var data = 
{
 id: 1,
 name: "John",
 sex: "M",
 maritalStatus: "M",
 dob:"01-01-1990",
 title:"Software Engineer",
 address:"VN",
 phoneNumber:"(123) 456-7890",
 email: "john@gmail.com"
};

console.log(Object.prototype.toString.call(data) ); //[object Object]


var data2 = [
{
 id: 1,
 name: "John",
 sex: "M",
 maritalStatus: "M",
 dob:"01-01-1990",
 title:"Software Engineer",
 address:"VN",
 phoneNumber:"(123) 456-7890",
 email: "john@gmail.com"
}
];


console.log(Object.prototype.toString.call(data2) ); //[object Array]

var data1 = [
               ["1", "John", "M", "M", "1990", "Software Engineer", "john@gmail.com", "(123) 456-7890"],
            ];

console.log(Object.prototype.toString.call(data1) );//[object Array]