我们需要看看Javascript中对象有什么方法/字段。
当前回答
你可以将此用于字符串和对象/数组
function print_r(obj){
return JSON.stringify(obj, null, "\t");
}
其他回答
可以使用console.debug(object)来实现这一点再简单不过了。如果你以此为生,这个技巧将为你每年节省数百个小时
虽然有点晚了,但这里有一个非常方便的函数,使用起来超级简单,允许您传递任意类型的参数,并将在浏览器控制台窗口中显示对象内容,就像您从JavaScript调用console.log一样——但是从PHP调用的
注意,你也可以使用标签通过传递" tag - yourtag "它将被应用,直到读取另一个标签,例如" tag - yournexttag "
/*
* Brief: Print to console.log() from PHP
* Description: Print as many strings,arrays, objects, and other data types to console.log from PHP.
* To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
* you can pass as many data as you want an this will still work.
*
* This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*
* A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
* detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
* be applied to all data after it.
*
* Example:
* consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3);
* Result:
* FirstTag '...data...'
* FirstTag '...data2...'
* SecTag '...data3...'
*/
function consoleLog(){
if(func_num_args() == 0){
return;
}
$tag = '';
for ($i = 0; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if(!empty($arg)){
if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
$tag = substr($arg,4);
}else{
$arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
echo "<script>console.log('".$tag." ".$arg."');</script>";
}
}
}
}
注意:func_num_args()和func_num_args()是php函数,用于读取动态数量的输入参数,并允许该函数从一个函数调用中有无限多个console.log请求
很多现代浏览器都支持以下语法:
JSON.stringify(myVar);
如果您使用的是firefox,那么firebug插件控制台是检查对象的绝佳方法
console.debug(myObject);
或者你可以像这样循环遍历属性(包括方法):
for (property in object) {
// do what you want with property, object[property].value
}
你可以简单地使用NPM包var_dump
npm install var_dump --save-dev
用法:
const var_dump = require('var_dump')
var variable = {
'data': {
'users': {
'id': 12,
'friends': [{
'id': 1,
'name': 'John Doe'
}]
}
}
}
// print the variable using var_dump
var_dump(variable)
这将打印:
object(1) {
["data"] => object(1) {
["users"] => object(2) {
["id"] => number(12)
["friends"] => array(1) {
[0] => object(2) {
["id"] => number(1)
["name"] => string(8) "John Doe"
}
}
}
}
}
链接:https://www.npmjs.com/package/@smartankur4u / vardump
以后谢谢我!
推荐文章
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何禁用文本选择使用jQuery?
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- 如何停止事件冒泡复选框点击
- PHP/MySQL插入一行然后获取id