不想在Javascript中打印Array数组

时间:2014-08-20 09:13:13

标签: javascript multidimensional-array

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

例如我的数组是: -

[
"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
}
]
]

我只想展示[“故事”,“任务”,“进行中”,“审核中”,“已完成”],没有别的。

请建议如何在javascript中处理此事?

4 个答案:

答案 0 :(得分:3)

在迭代array时,检查其中每个项目的type

for (var i =0; i< arr.length; i++) {
        if (typeof arr[i] === "string") {
          console.log(arr[i]);
        }
 }

更好的方法(受此answer启发)

for (var i =0; i< arr.length; i++) {
    if( Object.prototype.toString.call( arr[i] ) !== '[object Array]' ) {
       console.log(arr[i]);
}

答案 1 :(得分:2)

您可以使用JavaScript's instanceof operator遍历数组并检查每个值是否为数组。

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);

JSFiddle demo

> ["Stories", "Tasks", "In Progress", "In Review", "Completed"] 

答案 2 :(得分:0)

在更现代的浏览器中,这也有效:

array.filter(function(item){
  return typeof(item) !== "object";
});

答案 3 :(得分:0)

非常简单,有三行你可以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/