我想看看JavaScript对象的结构(用于调试)。PHP中有类似var_dump的东西吗?
当前回答
Firebug。
然后,在javascript中:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
现在你可以查看控制台,点击语句,看看里面有什么
其他回答
我写了这个JS函数dump()来像PHP的var_dump()一样工作。 要在警报窗口中显示变量的内容:dump(variable) 要在网页中显示变量的内容:dump(variable, 'body') 获取变量的字符串:dump(variable, 'none')
/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
out = '';
for (var i = 0; i < num; i++) {
out += str;
}
return out;
}
/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
v: The variable
howDisplay: "none", "body", "alert" (default)
recursionLevel: Number of times the function has recursed when entering nested
objects or arrays. Each level of recursion adds extra space to the
output to indicate level. Set to 0 by default.
Return Value:
A string of the variable's contents
Limitations:
Can't pass an undefined variable to dump().
dump() can't distinguish between int and float.
dump() can't tell the original variable type of a member variable of an object.
These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;
var vType = typeof v;
var out = vType;
switch (vType) {
case "number":
/* there is absolutely no way in JS to distinguish 2 from 2.0
so 'number' is the best that you can do. The following doesn't work:
var er = /^[0-9]+$/;
if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
out = 'int';
}
*/
break;
case "boolean":
out += ": " + v;
break;
case "string":
out += "(" + v.length + '): "' + v + '"';
break;
case "object":
//check if null
if (v === null) {
out = "null";
}
//If using jQuery: if ($.isArray(v))
//If using IE: if (isArray(v))
//this should work for all browsers according to the ECMAScript standard:
else if (Object.prototype.toString.call(v) === '[object Array]') {
out = 'array(' + v.length + '): {\n';
for (var i = 0; i < v.length; i++) {
out += repeatString(' ', recursionLevel) + " [" + i + "]: " +
dump(v[i], "none", recursionLevel + 1) + "\n";
}
out += repeatString(' ', recursionLevel) + "}";
}
else {
//if object
let sContents = "{\n";
let cnt = 0;
for (var member in v) {
//No way to know the original data type of member, since JS
//always converts it to a string and no other way to parse objects.
sContents += repeatString(' ', recursionLevel) + " " + member +
": " + dump(v[member], "none", recursionLevel + 1) + "\n";
cnt++;
}
sContents += repeatString(' ', recursionLevel) + "}";
out += "(" + cnt + "): " + sContents;
}
break;
default:
out = v;
break;
}
if (howDisplay == 'body') {
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
else if (howDisplay == 'alert') {
alert(out);
}
return out;
}
在JavaScript中等效的var_dump ?很简单,没有。
但这并不意味着你就无能为力了。就像一些人建议的那样,使用Firebug(或其他浏览器中的等效工具),但与其他人建议的不同的是,当你有(稍微)更好的工具console.dir时,不要使用console.log:
console.dir(object)
打印对象的所有属性的交互式列表。这 看起来与您在DOM选项卡中看到的视图相同。
Firebug。
然后,在javascript中:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
现在你可以查看控制台,点击语句,看看里面有什么
最常见的方式:
console.log(object);
但是我必须提到JSON。Stringify用于转储非浏览器脚本中的变量:
console.log( JSON.stringify(object) );
JSON。正如Simon Zyx指出的那样,stringify函数还支持内置的修饰。
例子:
var obj = {x: 1, y: 2, z: 3};
console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2
上面的代码片段将打印:
{
"x": 1,
"y": 2,
"z": 3
}
在caniuse.com上,您可以查看原生支持JSON的浏览器。Stringify函数:http://caniuse.com/json
您还可以使用Douglas Crockford库来添加JSON。旧浏览器上的stringify支持:https://github.com/douglascrockford/JSON-js
JSON文档。stringify: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
我希望这对你有帮助:-)
我提出这一点是为了帮助那些需要实用的东西的人,给你一个漂亮的、美化的(缩进的)JS节点的图片。对于节点,没有其他解决方案适合我(“周期性错误”或其他什么…)。这将引导您遍历DOM Node下的树(不使用递归),并为您提供深度、tagName(如果适用)和textContent(如果适用)。
在头节点下走过树时遇到的任何其他节点细节都可以根据自己的兴趣添加……
function printRNode( node ){
// make sort of human-readable picture of the node... a bit like PHP print_r
if( node === undefined || node === null ){
throwError( 'node was ' + typeof node );
}
let s = '';
// NB walkDOM could be made into a utility function which you could
// call with one or more callback functions as parameters...
function walkDOM( headNode ){
const stack = [ headNode ];
const depthCountDowns = [ 1 ];
while (stack.length > 0) {
const node = stack.pop();
const depth = depthCountDowns.length - 1;
// TODO non-text, non-BR nodes could show more details (attributes, properties, etc.)
const stringRep = node.nodeType === 3? 'TEXT: |' + node.nodeValue + '|' : 'tag: ' + node.tagName;
s += ' '.repeat( depth ) + stringRep + '\n';
const lastIndex = depthCountDowns.length - 1;
depthCountDowns[ lastIndex ] = depthCountDowns[ lastIndex ] - 1;
if( node.childNodes.length ){
depthCountDowns.push( node.childNodes.length );
stack.push( ... Array.from( node.childNodes ).reverse() );
}
while( depthCountDowns[ depthCountDowns.length - 1 ] === 0 ){
depthCountDowns.splice( -1 );
}
}
}
walkDOM( node );
return s;
}
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie