我正在将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());
我的结果是
[&#34; Facebook赞&#34;,&#34; Facebook推荐&#34;,&#34; Facebook发送&#34;,&#34; Twitter Tweet&#34;,&#34; LinkedIn分享&#34;,&#34; LinkedIn推荐&#34;,&#34; Google+ + 1&#34;,&#34; Google+ 份额&#34;,空]
这是小提琴example
答案 0 :(得分:4)
添加对自己属性的检查(不是从Object proptotype继承):
Object.prototype.toArray = function(){
var arr = [];
for (var i in this) {
if(this.hasOwnProperty(i))
arr.push(this[i]);
}
return arr;
}
答案 1 :(得分:3)
添加hasOwnProperty
支票。
for (var i in this) {
if (this.hasOwnProperty(i)) {
arr.push(this[i]);
}
}