不要在Javascript中打印Array of Array

Don't want to print Array of Array in Javascript

本文关键字:Array 打印 of Javascript      更新时间:2023-09-26

我有一个数组数组,我只是想打印外部数组而不是内部数组。

例如,我的数组是:-
[
"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";
});