不要在Javascript中打印Array of Array
Don't want to print Array of Array in Javascript
我有一个数组数组,我只是想打印外部数组而不是内部数组。
例如,我的数组是:-[
"Stories",
"Tasks",
"In Progress",
"In Review",
"Completed",
[
{
"divName": "content-container2",
"content": "us 2345",
"topPos": 109,
"leftPos": 150
},
{
"divName": "content-container3",
"content": "Description",
"topPos": 98,
"leftPos": 382
},
{
"divName": "content-container4",
"content": "12212",
"topPos": 110,
"leftPos": 644
}
]
]
我只想显示["Stories", "Tasks", "In Progress", "In Review", "Completed"],没有别的。
请建议如何处理这个东西在javascript?
在迭代array
时,检查其中每个项目的type
,如
for (var i =0; i< arr.length; i++) {
if (typeof arr[i] === "string") {
console.log(arr[i]);
}
}
一个更好的方法(灵感来自这个答案)
for (var i =0; i< arr.length; i++) {
if( Object.prototype.toString.call( arr[i] ) !== '[object Array]' ) {
console.log(arr[i]);
}
你可以遍历数组,并使用JavaScript的instanceof
操作符检查每个值是否为数组。
var array = [], // This is your array
result = []; // This is the result array
// Loop through each index within our array
for (var i = 0; i < array.length; i++)
/* If the value held at the current index ISN'T an array
* add it to our result array. */
if (!(array[i] instanceof Array))
result.push(array[i]);
// Log the result array
console.log(result);
<<p> JSFiddle演示/strong>。> ["Stories", "Tasks", "In Progress", "In Review", "Completed"]
非常简单,只用三行就可以对数组进行filter
:
// Arr is your Array :)
var result = arr.filter(function(value){
return typeof value != 'array' && typeof value != 'object';
});
// It shows ["Stories", "Tasks", "In Progress", "In Review", "Completed"]
console.log(result);
参见jsfiddle: http://jsfiddle.net/j4n99uw8/1/.
:您还可以扩展数组并在另一边使用:
Array.prototype.oneDimension = function(){
return this.filter(function(value){
return typeof value != 'array' && typeof value != 'object';
});
};
// In each array you can use it:
console.log( arr.oneDimension() );
console.log( ['9',['9'],['2']].oneDimension() ); // Only contains '9'.
查看此jsfiddle: http://jsfiddle.net/j4n99uw8/2/
在更现代的浏览器中,这也是有效的:
array.filter(function(item){
return typeof(item) !== "object";
});
相关文章:
- 使用javascript将动态表从一个html页面打印到另一个html页
- JavaScript打印功能使日历停止工作
- 如何为json对象中的段发送array[]
- esri javascript异步打印
- 文本框不是从Javascript/Asp.net中的对话框中打印出来的
- Array.length似乎不起作用;console.log则显示其他情况
- 如何迭代Array.prototype函数
- jQuery/JavaScript在线公文包表单-打印样式表
- 如何打印嵌套对象的所有值
- 在终端中运行 JavaScript 时(使用 rhino),如何使用 print() 函数在一行中打印
- Javascript 新的 Array 和 join() 方法
- Array.lenght = undefined
- 打印预览没有应用程序页眉和页脚的html表格
- Javascript setTimeout for an array
- 正在打印图表上的文本
- Rhino打印功能
- NodeJS API调用中Array中的Push和Pull元素
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- Angularjs:在TextArea中打印带有新行的Array模型
- 不要在Javascript中打印Array of Array