[英]how to print a javascript object's elements
i am new to javascript and i currently have an object
printed to console when i use the following code: 我是javascript新手,当我使用以下代码时,当前有一个打印到控制台的
object
:
clickEvents: {
click:function(target) {
console.log(target);
}
}
when i view console i can see the following object: 当我查看控制台时,我可以看到以下对象:
i am banging my head against a wall to write code that takes the object and prints it to a div using the .append()
method. 我将头撞在墙上以编写代码,该代码使用该对象,并使用
.append()
方法将其打印到div。 i am extermely new to working with javascript objects, and would appreciate any help trying to tease out an object and/or print the object data. 我是刚接触javascript对象的新手,并且非常感谢尝试挑逗对象和/或打印对象数据的任何帮助。
is events
the object name? events
是对象名称吗? would i tease out the eventDate using something like events->eventDate
? 我会使用
events->eventDate
类的东西来挑逗events->eventDate
吗?
I'm not sure if you have a div that you want to append to already, but you would do something like this -> 我不确定您是否要添加一个div,但是您会执行以下操作->
document.getElementById("toBeAppendedTo").innerHTML = target.events[0].eventDate;
where toBeAppendedTo
is the id of the div you're trying to add this text to. toBeAppendedTo
是您要向其中添加文本的div的ID。
append()
is a jquery function, not a javascript function. append()
是一个jquery函数,不是javascript函数。
That won't have any formatting and will just be the string value 07-28-2017
in a div. 那将没有任何格式,而只是div中的字符串值
07-28-2017
。
I've made this over ~15 minutes so it's imperfect; 我已经完成了大约15分钟,所以它并不完美; there are types and edge cases surely unaccounted for and the design of the function could be better - not to mention that performing all of this as a giant string and then setting that as HTML is likely bad practice (I'm used to React now, ha!).
肯定没有说明类型和边缘情况,函数的设计可能会更好-更不用说将所有这些都作为一个巨大的字符串执行,然后将其设置为HTML可能是不好的做法(我已经习惯了React,哈!)。 Regardless, this will iterate over any array or object you pass to it and print it all in a big
<ul>
recursively. 无论如何,这将遍历传递给它的任何数组或对象,并以大
<ul>
递归方式将其全部打印出来。
const targetEl = document.querySelector('.js-target')
if (!targetEl) return
// Small helper functions
const isObj = data => typeof data === 'object' && !Array.isArray(data) && data !== null
const isArr = data => Array.isArray(data)
const dataToHTML = (data, noNode = false) => {
if (isObj(data)) {
const accumulator = Object.entries(data).reduce((acc, set) => acc + `<li><strong>${set[0]}</strong>: ${dataToHTML(set[1], true)}</li>`, '')
return `<ul>${accumulator}</ul>`
}
else if (isArr(data)) {
const accumulator = data.reduce((acc, item) => acc + dataToHTML(item), '')
return `<ul>${accumulator}</ul>`
}
else return noNode ? data : `<li>${data}</li>`
}
const logHTML = dataToHTML(exampleData)
targetEl.innerHTML = logHTML
Assuming that your data/variable is named exampleData
. 假设您的数据/变量名为
exampleData
。
Any questions pop them in the comments :-) 任何问题都会在评论中弹出:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.