0

我正在将 JavaScript 对象转换为数组,但结果我得到了一个null

这是我的代码

<div id="a"></div>

Object.prototype.toArray = function(){
    var arr = [];
    for (var i in this) {
        arr.push(this[i]);        
    }
    return arr;
} 

var providers = {
            facebooklike: "Facebook Like",
            facebookrecommend : "Facebook Recommend",
            facebooksend : "Facebook Send",
            twittertweet : "Twitter Tweet",
            linkedinshare : "LinkedIn Share",
            linkedinrecommend : "LinkedIn Recommend",
            googleplusplusone : "Google+ +1",
            googleplusshare : "Google+ Share"
        };

var a = document.getElementById("a");
a.innerHTML = JSON.stringify(providers.toArray());

我的结果是

["Facebook Like","Facebook Recommend","Facebook Send","Twitter Tweet","LinkedIn Share","LinkedIn Recommend","Google+ +1","Google+ Share",null]

这是小提琴示例

4

2 回答 2

4

添加检查自己的属性(不是从 Object 属性继承的):

Object.prototype.toArray = function(){
    var arr = [];
    for (var i in this) {
        if(this.hasOwnProperty(i))
            arr.push(this[i]);        
    }
    return arr;
} 
于 2012-09-13T09:53:55.753 回答
3

添加hasOwnProperty检查。

for (var i in this) {
    if (this.hasOwnProperty(i)) {
        arr.push(this[i]);
    }        
}
于 2012-09-13T09:53:32.637 回答