gpt4 book ai didi

JavaScript 代码问题 : I am converting object to array

转载 作者:行者123 更新时间:2023-11-28 12:03:32 25 4
gpt4 key购买 nike

我正在将 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]

这是 fiddle example

最佳答案

添加对自身属性的检查(不是从对象原型(prototype)继承):

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

关于JavaScript 代码问题 : I am converting object to array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12403637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com